Editorial for Consecutive Neighbours
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Let be the indicator that values
and
occupy adjacent positions in the
permutation. The total score is
.
By linearity,
.
To compute the probability, glue and
into a single block. The block may be
ordered in
ways, and the remaining
objects (the block plus
other
values) may be permuted freely, so
.
A common mistake is to answer : after placing
, two of the remaining
slots look adjacent, but that count is wrong at the two endpoints of the array, where
has only one neighbour slot. Averaging over the position of
recovers
.
Therefore
.
The indicators are dependent (overlapping pairs cannot all be adjacent at once in general),
but linearity still applies. The implementation is .
Solution (C++)
#include <bits/stdc++.h>
using namespace std;
const int MOD = 1000000007;
long long modpow(long long a, long long e) {
long long r = 1;
a %= MOD;
while (e) {
if (e & 1) {
r = r * a % MOD;
}
a = a * a % MOD;
e >>= 1;
}
return r;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
if (n == 1) {
cout << 0 << "\n";
return 0;
}
long long sum = 0;
for (int i = 0; i < n - 1; i++) {
long long w;
cin >> w;
sum += w;
if (sum >= MOD) {
sum %= MOD;
}
}
sum %= MOD;
cout << 2 * sum % MOD * modpow(n, MOD - 2) % MOD << "\n";
}
Comments