C. Polycarp Restores Permutation
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
inputCopy
3
-2 1
outputCopy
3 1 2
inputCopy
5
1 1 1 1
outputCopy
1 2 3 4 5
inputCopy
4
-1 2 2
outputCopy
-1
思考&过程
第一次就想直接模拟,找到符合的就退出,结果第38个点就超时了。
WA代码:
#include<iostream>
using namespace std;
int main()
{
int n,i,j;
static int a[200010],b[200010],c[200010];
cin>>n;
for(i=1;i<=n-1;i++)
{
cin>>a[i];
}
bool t;
t=true;
i=1;
while((i<=n)&&(t))
{
for(j=1;j<=n;j++) c[j]=0;
bool tt=true;
b[1]=i;
c[b[1]]=1;
j=2;
while((j<=n)&&(tt))
{
b[j]=b[j-1]+a[j-1];
if((b[j]<=0)||(b[j]>n)||(c[b[j]]==1)) tt=false;
c[b[j]]=1;
j=j+1;
}
if (tt)
{
t=false;
for(int p=1;p<=n;p++) cout<<b[p]<<" ";
}
i=i+1;
}
if (t) cout<<"-1";
return 0;
}
之后队友提示其实找到第一个无重复就行,然后统一加上差值,就可以使数列落在1-n,AC代码:
#include<iostream>
using namespace std;
int main()
{
long long ans,n,i,j,minn;
static int a[200010],b[200010],p[200010];
cin>>n;
for(i=1;i<n;i++)
{
cin>>a[i];
p[i]=p[i-1]+a[i];
}
minn=p[0];
for(i=1;i<n;i++)
{
if (p[i]<minn) minn=p[i];
}
for(i=0;i<n;i++)
{
if(p[i]-minn+1>n||b[p[i]-minn+1])
{
cout<<"-1"<<endl;
return 0;
}
b[p[i]-minn+1]=1;
}
for(i=0;i<n;i++) cout<<p[i]-minn+1<<" ";
return 0;
}
还有个队友提出这题可以数学解,推出公式可求第一项。