题目:
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 题目分析:
我最开始看到时间为2s,我想可以枚举第一个位置的数是多少,从而推出其他数,并标记跟判断范围,但是居然不是TLE,而是直接WA了,很奇怪,至今没想明白,代码也附上吧,若有大佬找到了我这种方法的问题,欢迎评论,告诉菜鸡的我~~
数学方法:对于q数组求前缀和,可以得到s数组,因为qi = pi+1 - pi,所以可以推出si = pi+1 - p1,又因为p1+p2+p3+p4+...+pn = n * (n + 1) / 2,所以可以得到一个关于p1的式子,(n-1)p1 = p2 + p3 + ... + pn - s1 - s2 - ... - sn-1,就可以求出p1的值了,从而推出整个数组,然后再判断是否合法即可。最好手动推一下试试
代码:
正确数学方法代码:
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<map>
#define N 200005
#define LL long long
using namespace std;
LL n,s=0;
LL b[N],ans[N],sum[N];
int main()
{
map<int,int> vis;//必须要用map,不然会RE
sum[0]=0;
scanf("%lld",&n);
for(int i=1;i<n;i++)
{
scanf("%lld",&b[i]);
sum[i]=sum[i-1]+b[i];
s+=sum[i];
}
LL k=n*(1+n)/2;
ans[1]=(k-s)/n;
vis[ans[1]]=1;
if(ans[1]>n||ans[1]<1)
{
printf("-1");
return 0;
}
for(int i=2;i<=n;i++)
{
ans[i]=ans[i-1]+b[i-1];
if(ans[i]>n||ans[i]<1||vis[ans[i]]==1)
{
printf("-1");
return 0;
}
vis[ans[i]]=1;
}
for(int i=1;i<=n;i++)printf("%lld ",ans[i]);
return 0;
}
错误的方法代码(至今不明白,欢迎大佬来教教小弟我):
#include<iostream>
#include<cstring>
#include<cstdio>
#define N 200005
using namespace std;
int n;
int b[N],ans[N];
bool flag,vis[N];
int main()
{
scanf("%d",&n);
for(int i=1;i<n;i++)scanf("%d",&b[i]);
for(int i=1;i<=n;i++)
{
memset(vis,0,sizeof(vis));
ans[1]=i;
flag=0;
vis[i]=1;
for(int j=2;j<=n;j++)
{
ans[j]=ans[j-1]+b[j-1];
if(ans[j]>n||ans[j]<1||vis[ans[j]]==1)
{
flag=1;
break;
}
vis[ans[j]]=1;
}
if(!flag)
{
for(int j=1;j<=n;j++)printf("%d ",ans[j]);
return 0;
}
}
printf("-1");
return 0;
}