题目描述
给定n个各不相同的无序字母对(区分大小写,无序即字母对中的两个字母可以位置颠倒)。请构造一个有n+1个字母的字符串使得每个字母对都在这个字符串中出现。
输入输出格式
输入格式:
第一行输入一个正整数n。
以下n行每行两个字母,表示这两个字母需要相邻。
输出格式:
输出满足要求的字符串。
如果没有满足要求的字符串,请输出“No Solution”。
如果有多种方案,请输出前面的字母的ASCII编码尽可能小的(字典序最小)的方案
输入输出样例
输入样例#1:
4
aZ
tZ
Xt
aX
输出样例#1:
XaZtX
说明
【数据规模与约定】
不同的无序字母对个数有限,n的规模可以通过计算得到。
解释:因为要构造一个n+1的字符串,那么必然用到n条边,所以就是找到一条欧拉路,由离散数学的知识,我们很容易判读出是否存在,如果存在的话,选好根节点直接暴力搜就好啦
#include<bits/stdc++.h>
using namespace std;
#define res register int
#define LL long long
#define inf 0x3f3f3f3f
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9')s=s*10+ch-'0',ch=getchar();
return s*w;
}
const int N=257;
int G[N][N],depth[N],n,cnt,hen;
char tmp[N],rb[N*N];
inline void dfs(int x){
for(res i=0;i<N;i++)
if(G[x][i])G[x][i]=G[i][x]=0,dfs(i);
rb[n--]=x;
}
int main(){
n=read();
for(res i=1;i<=n;i++){
scanf("%s",tmp);
G[int(tmp[0])][int(tmp[1])]=G[int(tmp[1])][int(tmp[0])]=1;
depth[int(tmp[0])]++;
depth[int(tmp[1])]++;
}
for(res i=0;i<N;i++)
if(depth[i]&1){
cnt++;
if(!hen)hen=i;
}
if(!hen) for(res 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;
}