原题链接:
题目描述:
You are given a permutation aa of size nn and you should perform nn operations on it. In the ii-th operation, you can choose a non-empty suffix of aa and increase all of its elements by ii. How can we perform the operations to minimize the number of inversions in the final array?
Note that you can perform operations on the same suffix any number of times you want.
A permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array. A suffix is several consecutive elements of an array that include the last element of the array. An inversion in an array aa is a pair of indices (i,j)(i,j) such that i>ji>j and ai<ajai<aj.
Input
Each test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.
The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the size of the array.
The second line contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), the initial permutation aa.
It's guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.
Output
For each test case, print nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤n1≤xi≤n for each 1≤i≤n1≤i≤n) indicating that the ii-th operation must be applied to the suffix starting at index xixi. If there are multiple answers, print any of them.
题目大意:
给定一个长度为n的正整数数组,你需要进行n轮操作, 第i轮操作可以任意选择一个L,使得从第L个数到末尾所有的数都加上i。问如何操作可以使得操作完毕之后,数组内的逆序对数量最小。(可以重复选取一个L)。
解题思路:
开一个差分数组d,d[i]=a[i]-a[i - 1],那么如果要整个数组的逆序对最小,那么也就是说要使小于零的d[i]尽可能少,我们可以发现当你选择L进行操作时,只有d[L]会发生变化,又因为越靠后的操作,加的数就越大,所以我们每次都应该优先选择d[i]更大的i进行操作。
代码(CPP):
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e5 + 10;
const int INF = 0x3fffffff;
int n, a[maxn];
struct diff
{
int idx, v;
} d[maxn];
bool cmp(diff &a, diff &b)
{
return a.v > b.v;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << fixed;
cout.precision(18);
int t;
cin >> t;
while(t--)
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
if(i > 1)
d[i].v = a[i] - a[i - 1];
else
d[i].v = a[i];
d[i].idx = i;
}
sort(d + 1, d + 1 + n, cmp);
vector<int> ans;
int op = 1;
for (int i = 1; i <= n; i++)
{
if(d[i].v < 0)
{
d[i].v += op;
ans.push_back(d[i].idx);
op++;
}
else
ans.push_back(op);
}
for (int i = 0; i < ans.size(); i++)
{
if(i != 0)
cout << " ";
cout << ans[i];
}
cout << endl;
}
return 0;
}