There is a regular convex polygon with n vertices. The vertices are labeled from 0 to n - 1 in a clockwise direction, and each vertex has exactly one monkey. The following figure shows a convex polygon of 6 vertices.
Simultaneously, each monkey moves to a neighboring vertex. A collision happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge.
Return the number of ways the monkeys can move so that at least one collision happens. Since the answer may be very large, return it modulo `109
Input: n =3Output: 6Explanation:
There are 8 total possible movements.Two ways such that they collide at some point are:* Monkey 1 moves in a clockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 2 collide.* Monkey 1 moves in an anticlockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 3 collide.
Each monkey can move either clockwise or counterclockwise, so there are 2^n total ways. However, if all monkeys move in the same direction, there are no collisions (since they all rotate together). So, we subtract these 2 cases (all clockwise or all counterclockwise) from the total. The answer is (2^n - 2) modulo 1e9+7.
classSolution {
public:int monkeyMove(int n) {
constint mod =1e9+7;
longlong ans =1;
longlong base =2;
int exp = n;
while (exp) {
if (exp &1) ans = (ans * base) % mod;
base = (base * base) % mod;
exp >>=1;
}
ans = (ans -2+ mod) % mod;
return (int)ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funcmonkeyMove(nint) int {
mod:= int(1e9+7)
ans:=1base:=2exp:=nforexp > 0 {
ifexp&1==1 {
ans = ans*base%mod }
base = base*base%modexp>>=1 }
ans = (ans-2+mod) %modreturnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintmonkeyMove(int n) {
int mod = 1_000_000_007;
long ans = 1, base = 2;
int exp = n;
while (exp > 0) {
if ((exp & 1) == 1) ans = (ans * base) % mod;
base = (base * base) % mod;
exp >>= 1;
}
ans = (ans - 2 + mod) % mod;
return (int)ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funmonkeyMove(n: Int): Int {
val mod = 1_000_000_007
var ans = 1Lvar base = 2Lvar exp = n
while (exp > 0) {
if (exp and 1==1) ans = ans * base % mod
base = base * base % mod
exp = exp shr 1 }
ans = (ans - 2 + mod) % mod
return ans.toInt()
}
}
1
2
3
4
5
classSolution:
defmonkeyMove(self, n: int) -> int:
mod =10**9+7 ans = pow(2, n, mod)
return (ans -2) % mod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnmonkey_move(n: i32) -> i32 {
let m =1_000_000_007;
letmut ans =1i64;
letmut base =2i64;
letmut exp = n asi64;
while exp >0 {
if exp &1==1 {
ans = ans * base % m;
}
base = base * base % m;
exp >>=1;
}
((ans -2+ m) % m) asi32 }
}