http://codeforces.com/problemset/problem/1141/C
An array of integers p1,p2,…,pn is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3,1,2], [1], [1,2,3,4,5] and [4,3,1,2]. The following arrays are not permutations: [2], [1,1], [2,3,4].
Polycarp invented a really cool permutation p1,p2,…,pn of length n. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1 of length n−1, where qi=pi+1−pi.
Given n and q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.
Input
The first line contains the integer n (2≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1 integers q1,q2,…,qn−1 (−n<qi<n).
Output
Print the integer -1 if there is no such permutation of length n which corresponds to the given array q. Otherwise, if it exists, print p1,p2,…,pn. Print any such permutation if there are many of them.
Examples
Input
3
-2 1
Output
3 1 2
Input
5
1 1 1 1
Output
1 2 3 4 5
Input
4
-1 2 2
Output
-1
给出数字数量和相邻两项的差问是否能构成一个包含1到n所有数字的数组
假设第一个数字是0,求出当前数组所有数字记录最小值,然后将所有数字减去最小值加1即可;
然后遍历一次看是否满足条件。
注意求最小值时数字可能会很大(流下了不谨慎的泪水),这个时候一定不能满足条件直接退出循环。
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int n,d[200005],a[200005],vis[200005];
int main()
{
scanf("%d",&n);
for(int i=1;i<n;i++)
scanf("%d",d+i);
a[0]=0;
int mi=0;
int flag=1;
for(int i=1;i<n;i++)
{
a[i]=a[i-1]+d[i];
mi=min(mi,a[i]);
if(mi<-500000)
{
flag=0;
break;
}
}
if(!flag)
{
printf("-1\n");
return 0;
}
for(int i=0;i<n;i++)
a[i]=a[i]-mi+1;
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++)
{
vis[a[i]]++;
if(vis[a[i]]>1||a[i]>n)
{
flag=0;
break;
}
}
if(flag)
{
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
else
printf("-1\n");
}