Problem Statement
We have a sequence of N integers A~=~A0,~A1,~…,~AN−1.
Let B be a sequence of K×N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.
Find the inversion number of B, modulo 109+7.
Here the inversion number of B is defined as the number of ordered pairs of integers (i,~j)~(0≤i<j≤K×N−1) such that Bi>Bj.
Constraints
- All values in input are integers.
- 1≤N≤2000
- 1≤K≤109
- 1≤Ai≤2000
Input
Input is given from Standard Input in the following format:
N K A0 A1 … AN−1
Output
Print the inversion number of B, modulo 109+7.
Sample Input 1
2 2 2 1
Sample Output 1
3
In this case, B~=~2,~1,~2,~1. We have:
- B0>B1
- B0>B3
- B2>B3
Thus, the inversion number of B is 3.
Sample Input 2
3 5 1 1 1
Sample Output 2
0
A may contain multiple occurrences of the same number.
Sample Input 3
10 998244353 10 9 8 7 5 6 3 4 2 1
Sample Output 3
185297239
Be sure to print the output modulo 109+7.
思路:题意清晰,求 k - 1到 1 的和,注意取模;
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll mod = 1e9+7;
int num[2000+10];
int a[2000+10];
int b[2000+10];
int main()
{
ll n,k;
cin>>n>>k;
for(int i=0; i<n; i++)
cin>>num[i];
for(int i=0; i<n; i++)
{
int j=i+1;
while(j < n)
{
if(num[j] < num[i]) a[i]++;
j++;
}
if(!b[num[i]])
{
for(int k=0; k<n; k++)
{
if(num[k] < num[i])
b[num[i]]++;
}
}
}
// for(int i=0; i<n; i++) cout<<a[i]<<' '<<b[num[i]]<<endl;
ll ans=0;
ll sum=(k-1)*k/2;//放在下面的求ans语句中就会wa,求逆元也不行,遇到除法还是单独运算比较好.
sum = sum % mod;
for(int i=0; i<n; i++)
{
// ans += b[num[i]]*sum%mod;
// ans += k*a[i]%mod;
ans=(ans+k*a[i]%mod+b[num[i]]*sum%mod)%mod;
}
cout<<ans%mod;
return 0;
}