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−1 integers 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
题解:我们先让排列的第一个值先取0,因为后边差距是一定的,所以预先算出来每一个预处理的排列值,并且记录其中的最小值,如果最小值大于0的话,让其为0,其目的是保证最小值为1,然后让排列之中的每一个值减去那个最小值再加上1,即保证了最小值为1 !!! (排列之中的每一个数都随之变化,因为两两之间的差距是一定的,而我们就是根据差距预先算出来了一个预排列)如果排列之中的一个值不在范围之内或者这个值已经出现过,说明不符合题意,直接输出-1即可。
#include<bits/stdc++.h>
using namespace std;
map<int,int>mp;
const int maxn=200020;
int minn=0x3f3f3f3f;
int n,p[maxn],q[maxn];
int main()
{
cin>>n;
for(int i=0;i<n-1;i++)//q[i]记录的是两两之间的差距
cin>>q[i];
for(int i=0;i<n-1;i++)//让第一位预先为0,后序随之变化,因为差距时给定的
{
p[i+1]=p[i]+q[i];
minn=min(minn,p[i+1]);//记录最小值的目的时到后来保证所有数都是政正值
}
minn=min(0,minn);//如过每一位都大于等于0,要转换为0,即保证最小值为1
for(int i=0;i<n;i++)
{
p[i]=p[i]-minn+1;//减去最小值再加1的目的是让最小的那个值为1
if(p[i]<1||p[i]>n||mp[p[i]])//不在范围之内或者这个数已经出现过直接输出-1
{
cout<<"-1"<<endl;
return 0;
}
mp[p[i]]++;//标记该数已经出现
}
for(int i=0;i<n;i++)
cout<<p[i]<<" ";
cout<<endl;
return 0;
}