[Luogu1341]无序字母对(欧拉回路)

按题意给定字符串建无向图,找欧拉回路

按照定义,当没有奇数度点或者只有2个奇数度点时才有欧拉回路

Code

#include <cstdio>
#include <algorithm>
#define N 666
using namespace std;

int n,g[N][N],cnt,in[N],st,path[N];

inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

int f(char ch){
	if(ch>='a'&&ch<='z') return ch-'a'+27;
	else return ch-'A'+1;
}

void dfs(int i){
	for(int j=1;j<=52;++j)//字典序最小
		if(g[i][j]){
			g[i][j]=g[j][i]=0;
			dfs(j);
		}
	path[++cnt]=i;
}

int main(){
	n=read();
	for(int i=1;i<=n;++i){
		char s[10];
		scanf("%s
",s);
		int u=f(s[0]),v=f(s[1]);
		++in[u],++in[v];
		g[u][v]=g[v][u]=1;
	}
	for(int i=52;i>=1;--i) if(in[i]&1) cnt++,st=i;
	if(cnt!=0&&cnt!=2){
		printf("No Solution
");
		return 0;
	}
	if(!cnt) for(int i=1;i<=52;++i) if(in[i]){st=i;break;}//字典序最小
	cnt=0;
	dfs(st);
	for(int i=cnt;i>=1;--i) printf("%c",(path[i]<=26)?'A'+path[i]-1:'a'+path[i]-27);
	return 0;
}
原文地址:https://www.cnblogs.com/void-f/p/9026338.html