洛谷P1341 无序字母对
众所周知, 无向图的一笔画条件为 所有点的度为偶数 或 有且只有两个点的度为奇数
但是,怎么输出一笔画的路径?
https://blog.csdn.net/stillxjy/article/details/51956183
介绍了一种好用的Hierholzer 算法;
大体是利用栈的思想记录.
附上压行代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = (26 + 2) << 1;
inline int getnum(char ch)
{
return ch >= 'a' ? ch - 'a' + 27: ch - 'A';
}
int N;
int g[MAXN][MAXN];
int deg[MAXN];
vector<int> ans;
void dfs(int cur){
for(int i = 0; i < MAXN; i++) if(g[cur][i]){
g[cur][i] = g[i][cur] = false ;
dfs(i);
}
ans.push_back(cur);
}
int main()
{
cin>>N;
for(int i = 1; i <= N; i++){
char u, v;
scanf(" %c%c", &u, &v);
g[getnum(u)][getnum(v)] = g[getnum(v)][getnum(u)] = true;
++deg[getnum(u)], ++deg[getnum(v)];
}
int cnt = 0, fir;
for(int i = 0; i < MAXN; i++) if(deg[i] & 1) ++cnt;
if(!((cnt == 0) || (cnt == 2))) return puts("No Solution"), 0;
if(cnt == 2) for(int i = 0; i < MAXN; i++) {if(deg[i] & 1) {fir = i; break;}}
else for(int i = 0; i < MAXN; i++) if(deg[i]) {fir = i; break;}
dfs(fir);
for(int i = ans.size() - 1; i >= 0; --i)
putchar((char) ans[i] >= 27 ? ans[i] - 27 + 'a' : ans[i] + 'A');
return 0;
}