PAT TOP 1027 Larry and Inversions (35)
問題描述:
1027 Larry and Inversions (35 分)
Larry just studied the algorithm to count number of inversions. He's very interested in it. He's considering another problem: Given a permutation of integers from 1 to n, how many inversions it has if we reverse one of its subarray?
Formally speaking, given an integer array a (indices are from 0 to n−1) which contains a permutation of integers from 1 to n, two elements a[i] and a[j] form an inversion
Input Specification:
Each input file contains one test case. Each case consists of a positive integer n (≤1,000) in the first line, and a permutation of integers from 1 to n in the second line. The numbers in a line are separated by a single space.
Output Specification:
For each test case, output n(n+1)/2 integers in a single line. The results are for reversing subarray indicating by all possible pairs of indices 0≤i≤j<n in i-major order -- that is, the first n results are for the reverse of subarrary [0..0], [0..1], ...[0..n−1]; the next n−1 results are for the reverse of subarry [1..1], [1..2],..., [1..n−1] and so on.
All the numbers in a line must be separated by a single space, with no extra space at the beginning or the end of the line.
Sample Input:
3
2 1 3
Sample Output:
1 0 2 1 2 1
Hint:
The original array is { 2, 1, 3 }.
- Reversing subarray [0..0] makes { 2, 1, 3 } which has 1 inversion.
- Reversing subarray [0..1] makes { 1, 2, 3 } which has 0 inversion.
- Reversing subarray [0..2] makes { 3, 1, 2 } which has 2 inversions.
- Reversing subarray [1..1] makes { 2, 1, 3 } which has 1 inversion.
- Reversing subarray [1..2] makes { 2, 3, 1 } which has 2 inversions.
- Reversing subarrays [2..2] makes { 2, 1, 3 } which has 1 inversion.
時隔一年的pat top博主又回來啦。這一題是和逆序數相關的問題,掌握必要的數學知識很重要。
事實上,對於一個排列(a[1],a[2]..a[n]),若它的逆序數為S,則它的逆排列(a[n],a[n-1]..a[1])的逆序數為S'=n(n-1)/2-S。更進一步,對於它的一個逆序數為T的子排列(a[i],a[i+1]...a[j]),若將其逆序,使(a[1]...a[i],a[i+1]...a[j]...a[n]),成為(a[1]...a[j],a[j-1]...a[i]...a[n]),則(a[1]...a[j],a[j-1]...a[i]...a[n])的逆序數為S''=S-2T+(j-i+1)(j-i)/2,這兩個結論讀者自證。
順便感謝一下大家對博主的支援。
AC程式碼:
#include<bits/stdc++.h>
using namespace std;
int n,k;
vector<int> v;
vector<int> vl;
int main()
{
// freopen("data.txt","r",stdin);
scanf("%d",&n);
vl.resize(n*n,0);
for(int i=0;i<n;i++)
{
scanf("%d",&k);
v.emplace_back(k-1);
}
int brev=0;
for(int i=0;i<n;++i)
{
int rev=0;
for(int j=i;j<n;++j)
{
if(v[j]<v[i])
rev++;
vl[i*n+j]=rev;
}
brev+=rev;
}
bool flag=false;
for(int i=0;i<n;i++)
for(int j=i;j<n;j++)
{
if(i==j)
{
if(flag)
printf(" ");
else
flag=true;
printf("%d",brev);
}
else
{
int drev=0;
for(int t=i;t<j;t++)
drev+=vl[t*n+j];
printf(" %d",brev-2*drev+(j-i)*(j-i+1)/2);
}
}
return 0;
}