time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
An array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].
Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.
Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.
Input
The first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).
Output
Print the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.
Examples
input
Copy
3 -2 1
output
Copy
3 1 2
input
Copy
5 1 1 1 1
output
Copy
1 2 3 4 5
input
Copy
4 -1 2 2
output
Copy
-1
意义就是给了数组q,q是根据式子 qi=pi+1−pi,得到的然后让求原数组p。
这里先假设p1 = 1,也可以设成别的数,然后根据pi+1 = pi + qi,得到后续的数,然后又因为原数组的范围是1~n故,最小值应该是1,如果最小值不为1说明第一个元素也不是1,每个元素就有一个偏移量,(最小位置上的值 + 偏移量 = 1),偏移量 = 1 -
最小位置上的值,然后每个元素都加上偏移量即可得到原数组p;
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int p[N],a[N];
int main()
{
int n;
map<int,int> mmp;
scanf("%d",&n);
for (int i=1;i<n;i++)
scanf("%d",&p[i]);
a[1] = 1;
int temp = 0x3f3f3f3f;
for (int i=1;i<n;i++)
{
a[i+1] = p[i] + a[i];
temp = min(temp,a[i+1]);
}
temp = min(temp,1);
int k = 1 - temp;
for (int i=1;i<=n;i++)
{
a[i] += k;
mmp[a[i]]++;
}
for (int i=1;i<=n;i++)
{
if (mmp[i]!=1)
{
printf("-1\n");
return 0;
}
}
for (int i=1;i<=n;i++)
printf("%d ",a[i]);
puts("");
return 0;
}