您的位置:首页 > 其它

单词,紫书P169UVa10129(有向图求欧拉路径问题,并查集求连通分支)

2017-10-08 19:13 211 查看
非常经典的有向图求欧拉路径问题。有向图存在欧拉路径的条件有两个:

1.最多只能有两个点的入度不等于出度,而且必须是其中一个点的出度恰巧比入度大1(把它作为起点),另一个点的入度比出度大1(把它作为终点)。

2.底图(忽略了方向之后的无向图)必须是连通的。

而判断图的连通性,并查集可以说是非常优良的算法。直接贴刘源码。不过其中刘源码并查集的find函数并没有路径压缩,可能是因为本题节点数比较少。

// UVa10129 Play on Words
// Rujia Liu

#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;

const int maxn = 1000 + 5;

int pa[256];
int findset(int x) { return pa[x] != x ? pa[x] = findset(pa[x]) : x; }

int used[256], deg[256];

int main() {
int T;
scanf("%d", &T);
while(T--) {
int n;
char word[maxn];

scanf("%d", &n);
memset(used, 0, sizeof(used));
memset(deg, 0, sizeof(deg));
for(int ch = 'a'; ch <= 'z'; ch++) pa[ch] = ch;
int cc = 26;

for(int i = 0; i < n; i++) {
scanf("%s", word);
char c1 = word[0], c2 = word[strlen(word)-1];
deg[c1]++;
deg[c2]--;
used[c1] = used[c2] = 1;
int s1 = findset(c1), s2 = findset(c2);
if(s1 != s2) { pa[s1] = s2; cc--; }
}

vector<int> d;
for(int ch = 'a'; ch <= 'z'; ch++) {
if(!used[ch]) cc--;
else if(deg[ch] != 0) d.push_back(deg[ch]);
}
bool ok = false;
if(cc == 1 && (d.empty() || (d.size() == 2 && (d[0] == 1 || d[0] == -1)))) ok = true;
if(ok) printf("Ordering is possible.\n");
else printf("The door cannot be opened.\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: