P1341 无序字母对

欧拉回路

#include <bits/stdc++.h>
#define inf 2333333333333333
#define N 1000010
#define p(a) putchar(a)
#define For(i,a,b) for(int i=a;i<=b;++i)
//by war
//2020.8.6
using namespace std;
int n,m,cnt,tot;
char s,x,y;
char ans[N];
map<char,int>d;
map<char,map<char,char> >f;
void in(int &x){
    int y=1;char c=getchar();x=0;
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    x*=y;
}
void o(int x){
    if(x<0){p('-');x=-x;}
    if(x>9)o(x/10);
    p(x%10+'0');
}

void dfs(char x){
    for(int i='A';i<='z';i++){
        if(f[x][i]>=1){
            f[x][i]--;
            f[i][x]--;
            dfs(i);
        }
    }
    ans[++cnt]=x;
}

signed main(){
    in(m);
    For(i,1,m){
        cin>>x>>y;
        f[x][y]++;
        f[y][x]++;
        d[x]++;d[y]++;
    }
    for(char i='A';i<='z';i++){
        if(d[i]&1){
            tot++;
        }
    }
    if(tot==1 || tot>2){
        puts("No Solution");
        return 0;
    }
    for(char i='A';i<='z';i++){
        if(d[i]>0){
            s=i;
            break;
        }
    }
    for(char i='A';i<='z';i++){
        if(d[i]&1){
            s=i;
            break;
        }
    }
    dfs(s);
    for(int i=cnt;i;i--){
        p(ans[i]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/war1111/p/13448594.html