Description
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
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-n的每一個數都要出現.
想到這里,覺得這個題也不難呀,二分枚舉第一個數然后根據前后的差值不斷的向后遞推就好了,不過注意判重。
如果第一個數太大了,那么必然會出現數組中的某一個數越界,那么就繼續二分左區間,否則就二分右區間。
而在某一個數作為第一個數的時候出現了某一個數重復出現的情況,則說明這個數組無法還原.
代碼區
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include <vector>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int Max = 5e5 + 5;
int v[Max];
;
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
for (int i = 1; i < n; i++)
{
scanf("%d", v + i);
}
int l, r;
if (v[1] > 0)l = 1, r = n - v[0]; //若前兩個數的差為正數,那么第一個數的小於n-v[0],因為第二個數不可以超過n
else l = 1 - v[0], r = n; //若前兩個數的差為負數,那么第一個數一定要大於1+v[0]
vector<int>q; //存數據
bool vis[Max]; //vis[i]記錄數字i是否出現
int flag = false, gg = false; //flag == true代表成功,gg = true代表失敗
while (l <= r) //二分
{
int mid = (l + r) / 2;
memset(vis, false, sizeof(vis));
vis[mid] = true; //表示mid出現
q.push_back(mid);
int next; //記錄序列下一個數
for (int i = 1; i < n;i++)
{
next = q.back() + v[i]; //記錄下一個數
if (1 <= next && next <= n && !vis[next])//當前數不重復,且在范圍[1,n]內
{
q.push_back(next);
vis[next] = true;
if (q.size() == n) flag = true;
}
else
{
if (1 <= next && next <= n && vis[next])gg = true; //出現重復,代表這個序列不可能成了
break;
}
}
if (gg || flag) break; //到達目的或者無法實現
q.clear(); //當前作為一個數的數失敗,則繼續二分
if (next > n)r = mid - 1; //第一個數太小導致越界
else l = mid + 1; //第一個數太大導致越界
}
if (gg)
{
printf("-1\n");
}
else
{
if(flag)
{
for (int i = 0;i < n - 1; i++)
{
printf("%d ", q[i]);
}
printf("%d\n", q[n - 1]);
}
else
{
printf("-1\n");
}
}
}
return 0;
}