CSU-暑假集训题 Polycarp Restores Permutation
题目链接: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.
3 -2 1
3 1 2
5 1 1 1 1
1 2 3 4 5
4 -1 2 2
Output
-1
思路
这个方法很巧妙,是别人想出来的,让我不禁感叹自己思想的贫瘠。
因为这个序列是固定的,即1到n,假设第一个数变为1,然后计算出后面数,得到一个序列,这个序列的最小值一定是1,然后其他的数加上这个差值。
AC代码
//巧妙的数学方法 #include<iostream> using namespace std; int a[200020],pos[200020]; int main(){ int n; cin>>n; int num; a[0]=1; int minn=1; for(int i=1;i<n;i++){ cin>>num; a[i]=num+a[i-1]; if(a[i]<minn)minn=a[i]; } int cha=1-minn; if(cha!=0){ for(int i=0;i<n;i++){ a[i]=a[i]+cha; } } for(int i=0;i<n;i++){ if(a[i]<=0||a[i]>n||pos[a[i]]) { cout<<-1<<endl; return 0; } pos[a[i]]=1; } for(int i=0;i<n-1;i++){ cout<<a[i]<<" "; } cout<<a[n-1]<<endl; return 0; }

浙公网安备 33010602011771号