Skip to content

Commit 0c740c9

Browse files
authored
Create City Tour Problem
1 parent b947cb9 commit 0c740c9

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

Mathematics/City Tour Problem

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
'''
2+
There are A cities numbered from 1 to A. You have already visited M cities, the indices of which are given in an array B of M integers.
3+
4+
If a city with index i is visited, you can visit either the city with index i-1 (i >= 2) or the city with index i+1 (i < A) if they are not already visited.
5+
Eg: if N = 5 and array M consists of [3, 4], then in the first level of moves, you can either visit 2 or 5.
6+
7+
You keep visiting cities in this fashion until all the cities are not visited.
8+
Find the number of ways in which you can visit all the cities modulo 10^9+7.
9+
10+
Input Format
11+
12+
The 1st argument given is an integer A, i.e total number of cities.
13+
The 2nd argument given is an integer array B, where B[i] denotes ith city you already visited.
14+
Output Format
15+
16+
Return an Integer X % (1e9 + 7), number of ways in which you can visit all the cities.
17+
Constraints
18+
19+
1 <= A <= 1000
20+
1 <= M <= A
21+
1 <= B[i] <= A
22+
For Example
23+
24+
Input:
25+
A = 5
26+
B = [2, 5]
27+
Output:
28+
6
29+
30+
Explanation:
31+
All possible ways to visit remaining cities are :
32+
1. 1 -> 3 -> 4
33+
2. 1 -> 4 -> 3
34+
3. 3 -> 1 -> 4
35+
4. 3 -> 4 -> 1
36+
5. 4 -> 1 -> 3
37+
6. 4 -> 3 -> 1
38+
'''
39+
40+
Solution:
41+
42+
class Solution:
43+
# @param A : integer
44+
# @param B : list of integers
45+
# @return an integer
46+
def solve(self, A, B):
47+
v = []
48+
old = 0
49+
for i in B:
50+
v.append(i-old-1)
51+
old = i
52+
53+
v.append(A-old)
54+
55+
56+
t = 0
57+
for i in v:
58+
if i>0:
59+
t+=i
60+
61+
res = 1
62+
for i in range(t):
63+
res = (res*(i+1))%1000000007
64+
65+
66+
s = 0
67+
for i in v[1:-1]:
68+
if i>0:
69+
s+=(i-1)
70+
71+
for i in range(s):
72+
res = (res*2)%1000000007
73+
74+
tp = 1
75+
for i in v:
76+
if i>1:
77+
for j in range(i):
78+
tp = (tp*(j+1))%1000000007
79+
i = 1000000005
80+
while i:
81+
if i%2==1:
82+
res = (res*tp)%1000000007
83+
tp = (tp*tp)%1000000007
84+
i = int(i/2)
85+
return res
86+

0 commit comments

Comments
 (0)