Polycarp Restores Permutation

https://codeforces.com/contest/1141/problem/C

题解:

a为给定数组

b为待求数组

b[i+1]=b[i]+a[i];

其中b[1]一定为零,当前的其他元素为相对于b[1]的相对差值相同与需要求的数组的与b[1]的相对差值;

因为b是一个排列,所以最小为1,找到b中最小的元素(并且小于等于0),算出它与1的差值,其他元素都加上这个差值;

然后判断有木有重复和超过n的数。

/*
*@Author:   STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=200000+10;
const int M=100000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,q;
int ans,cnt,flag,temp,sum;
int a[N];
int b[N];
bool vis[N];
char str;
struct node{};
void dfs(int x){
    if(x>=n){
        for(int i=1;i<=n;i++){
            printf("%d%c",b[i]," \n"[i==n]);
        }
        exit(0);
        return ;
    }
    b[x+1]=a[x]+b[x];//cout<<x<<" "<<b[x+1]<<endl;
    if(b[x+1]>0&&b[x+1]<=n&&vis[b[x+1]]==0){
        vis[b[x+1]]=1;
        dfs(x+1);
        vis[b[x+1]]=0;
    }
}
int main()
{
#ifdef DEBUG
	freopen("input.in", "r", stdin);
	//freopen("output.out", "w", stdout);
#endif
    //ios::sync_with_stdio(false);
    //cin.tie(0);
    //cout.tie(0);
    //scanf("%d",&t);
    //while(t--){
    scanf("%d",&n);
    int minl=INF;
    for(int i=1;i<n;i++){
        scanf("%d",&a[i]);
        b[i+1]=a[i]+b[i];
        minl=min(minl,b[i+1]);
    }
    minl=min(minl,0);
    ans=abs(minl)+1;
    set<int>st;
    for(int i=1;i<=n;i++){
        b[i]+=ans;
        if(b[i]<=0||b[i]>n){
            cout<<-1<<endl;
            return 0;
        }
        st.insert(b[i]);
    }
    if(st.size()==n){
        for(int i=1;i<=n;i++){
            printf("%d%c",b[i]," \n"[i==n]);
        }
    }else{
        cout<<-1<<endl;
    }


    //}

#ifdef DEBUG
	printf("Time cost : %lf s\n",(double)clock()/CLOCKS_PER_SEC);
#endif
    //cout << "Hello world!" << endl;
    return 0;
}

 

全部评论

相关推荐

03-04 07:14
门头沟学院 C++
黑皮白袜臭脚体育生:老板:都给工作机会了还想要工资,哪来这么多好事
点赞 评论 收藏
分享
03-26 13:04
已编辑
电子科技大学 算法工程师
xiaowl:你这个简历“条目上”都比较有深度性,但是实际上面试官又没法很好的评估你是怎么达到很多看上去很厉害的结果的。要避免一些看上去很厉害的包装,比如高效的内存复用策略的表达,如果仅是简单的一些内存共享机制,而且面试上也没有深挖的空间,就不要这样表达。比如,工程化模式本质上可能就是定义了一些abstract class,那也就没特别多值得讲的内容。建议简历上应该侧重那些你花了大量时间和精力解决、研究的问题,不要过分追求“丰富”,而是关注在技术深入度、问题解决能力的表现上。
没有实习经历,还有机会进...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务