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,,qn1 of length n1, where qi=pi+1pi

.

Given n

and q=q1,q2,,qn1

, help Polycarp restore the invented permutation.

Input

The first line contains the integer n

(2n2105) — the length of the permutation to restore. The second line contains n1 integers q1,q2,,qn1 (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,假设第一个数变为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;
} 

 

posted @ 2019-07-25 14:58  小小笼包包  Views(113)  Comments(0)    收藏  举报