P1341 无序字母对(欧拉路径+输出最小字典序)

传送门

题解:根据题意分析出是让输出一个最小字典序,首先建立好一些欧拉路径的前提,这个题还得判下图是否是联通的,用并查集判。

附上代码:


#include<bits/stdc++.h>

using namespace std;

const int N=257;

int n;
int f[N];
int G[N][N],depth[N],hen;
char tmp[N],rb[N*N];

int find(int x)
{
    if(x!=f[x]){
        return f[x]=find(f[x]);
    }
}

void dfs(int x)
{
    for(int i=0;i<N;i++){
        if(G[x][i]){
            G[x][i]=G[i][x]=0;
            dfs(i);
        }
    }
    rb[n--]=x;
}

int main()
{
    scanf("%d",&n);
    for(int i=0;i<N;i++){
        f[i]=i;
    }
    for(int i=1;i<=n;i++){
        scanf("%s",tmp);
        G[tmp[0]][tmp[1]]=G[tmp[1]][tmp[0]]=1;
        int fx=find(tmp[0]),fy=find(tmp[1]);
        f[fy]=fx;
        depth[tmp[0]]++;
        depth[tmp[1]]++;
    }
    int ans=0;
    for(int i=0;i<N;i++){
        if(f[i]==i&&depth[i]){
            ans++;
        }
    }
    if(ans!=1){
        puts("No Solution");
        return 0;
    }
    int cnt=0;
    for(int i=0;i<N;i++){
        if(depth[i]&1){
            cnt++;
            if(!hen){
                hen=i;
            }
        }
    }
    if(!hen){
        for(int i=0;i<N;i++){
            if(depth[i]){
                hen=i;
                break;
            }
        }
    }
    if(cnt&&cnt!=2){
        puts("No Solution");
        return 0;
    }
    dfs(hen);
    puts(rb);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhouzi2018/article/details/82751428