F. Restore the Permutation by Sorted Segments(想法)

http://codeforces.com/contest/1343/problem/F

题意:

有一个不知道的排序,对于每个前缀 i [ 2 , n ] i\in[2,n] ,有一个排序好的后缀(大于1的长度,长度不定),现在给出这n-1个后缀,求原排序。

  • n最大200

解析:

枚举第一个,那么就可以一个一个推出下一个

代码:

/*
 *  Author : Jk_Chen
 *    Date : 2020-04-21-23.37.53
 */
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define rep(i,a,b) for(int i=(int)(a);i<=(int)(b);i++)
#define per(i,a,b) for(int i=(int)(a);i>=(int)(b);i--)
#define mmm(a,b) memset(a,b,sizeof(a))
#define pb push_back
#define pill pair<int, int>
#define fi first
#define se second
void test(){cerr<<"\n";}
template<typename T,typename... Args>void test(T x,Args... args){cerr<<x<<" ";test(args...);}
const LL mod=1e9+7;
const int maxn=1e5+9;
const int N=1e5+9;
const int inf=0x3f3f3f3f;
LL rd(){ LL ans=0; char last=' ',ch=getchar();
    while(!(ch>='0' && ch<='9'))last=ch,ch=getchar();
    while(ch>='0' && ch<='9')ans=ans*10+ch-'0',ch=getchar();
    if(last=='-')ans=-ans; return ans;
}
#define rd rd()
/*_________________________________________________________begin*/

int n;
int ans[209];
unordered_set<int>S[209],TMP[209];
bool used[209],pre[209];
bool check(int fi){
    rep(i,2,n){
        used[i]=pre[i]=0;
        if(S[i].count(fi)){
            S[i].erase(fi);
            pre[i]=1;
        }
    }
    ans[1]=fi;

    rep(i,2,n){
        bool found=0;
        rep(j,2,n){
            if(used[j])continue;
            if(S[j].size()==1&&pre[j]==1){
                ans[i]=*S[j].begin();
                found=1;
                break;
            }
        }
        if(!found)return 0;
        rep(j,2,n){
            if(used[j])continue;
            if(pre[j]){
                if(!S[j].count(ans[i])){
                    return 0;
                }
                S[j].erase(ans[i]);
                if(S[j].empty())used[j]=1;
            }
            else{
                if(S[j].count(ans[i])){
                    S[j].erase(ans[i]);
                    pre[j]=1;
                }
            }
        }
    }
    return 1;
}

int main(){
    int t=rd;
    while(t--){
        n=rd;
        rep(i,2,n){
            int k=rd;
            TMP[i].clear();
            while(k--)TMP[i].insert(rd);
        }
        rep(i,1,n){
            rep(j,2,n)S[j]=TMP[j];
            if(check(i)){
                rep(j,1,n)printf("%d%c",ans[j]," \n"[j==n]);
                break;
            }
        }

    }
    return 0;
}

/*_________________________________________________________end*/

发布了790 篇原创文章 · 获赞 348 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/jk_chen_acmer/article/details/105693158