欧拉回路嘛…也叫一笔画,当度为奇数的点有0个或2个时有解,其他情况就“No Solution”。
由于要字典序最小的方案,我们从最小的字母开始遍历,然后记录答案即可。
Code:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;
int n,len=0;
bool a[60][60];
int d[60];
char ans[2010];
inline int num(char x)
{
if(x>='A' && x<='Z') return x-'A'+1;
else return x-'a'+27;
}
inline char word(int x)
{
if(x>=1 && x<=26) return x-1+'A';
else return x-27+'a';
}
void dfs(int x)
{
for(int y=1;y<=52;y++)
{
if(a[x][y])
{
a[x][y]=a[y][x]=0;
dfs(y);
}
}
ans[len--]=word(x);
}
int main()
{
scanf("%d",&n); len=n;
for(int i=1;i<=n;i++)
{
char s[10];scanf("%s",s);
int x=num(s[0]),y=num(s[1]);
d[x]++;d[y]++;
a[x][y]=a[y][x]=true;
}
int p,tot=0;
for(int i=1;i<=52;i++)
if(d[i]&1)
{
p=min(p,i);
tot++;
}
if(tot!=0 && tot!=2)
{
printf("No Solution");
return 0;
}
if(!tot)
for(int i=1;i<=52;i++)
if(d[i])
{
p=i;
break;
}
dfs(p);
printf("%s",ans);
}