UVa872 - Ordering(拓扑排序)

简介: UVa872 - Ordering(拓扑排序)
#include <cstdio>#include <cstring>#include <cctype>#include <map>usingnamespacestd;
constintN=220;
constintM=30;
charbuf[N];
boolvis[N];
intt, n;
intg[M][M];
map<char, int>chMap;
map<int, char>intMap;
charans[M];
intp[N], r[N];
voidinput();
voidtoposort(intdep);
boolisCycle();
intfind(intx);
boolUnion(intu, intv);
voidsolve();
intmain()
{
#ifndef ONLINE_JUDGEfreopen("e:\\uva_in.txt", "r", stdin);
#endifintcas;
scanf("%d", &cas);
gets(buf);
while (cas--) {
input();
solve();
if (cas) printf("\n");
    }
return0;
}
voidinput()
{
gets(buf);
gets(buf);
chMap.clear();
intMap.clear();
for (inti=0, len=strlen(buf); i<len; i++) {
if (isalpha(buf[i])) {
intsize=chMap.size();
chMap[buf[i]] =size;
intMap[size] =buf[i];
        }
    }
memset(g, 0x00, sizeof(g));
gets(buf);
for (inti=0, len=strlen(buf); i<len; i+=4) {
chartmp[4];
sscanf(&buf[i], "%s", tmp);
intu=chMap[tmp[0]], v=chMap[tmp[2]];
g[u][v] =1;
    }
n=chMap.size();
}
intfind(intx)
{
introot=x;
while (p[root] !=root) {
root=p[root];
    }
while (p[x] !=root) {
inttmp=x;
x=p[x];
p[tmp] =root;
    }
returnroot;
}
boolUnion(intu, intv)
{
intpu=find(u), pv=find(v);
if (pu==pv) returnfalse;
if (r[pu] <r[pv]) p[pu] =pv;
else {
p[pv] =pu;
if (r[pu] ==r[pv]) r[pu]++;
    }
returntrue;
}
boolisCycle()
{
for (inti=0; i<n; i++) {
p[i] =i;
r[i] =0;
    }
for (inti=0; i<n; i++) {
for (intj=0; j<n; j++) {
if (g[i][j]) {
if (!Union(i, j)) returnfalse;
            }
        }
    }
returntrue;
}
voidtoposort(intdep)
{
if (dep==n) {
for (inti=0; i<n; i++) {
if (i) printf(" ");
printf("%c", ans[i]);
        }
printf("\n");
return;
    }
for (inti=0; i<n; i++) {
if (vis[i]) continue;
intj;
for (j=0; j<n; j++) {
if (j!=i&&!vis[j] &&g[j][i]) break;
        }
if (j>=n) {
vis[i] =true;
ans[dep] =intMap[i];
toposort(dep+1);
vis[i] =false;
        }
    }
}
voidsolve()
{
if (!isCycle()) {
printf("NO\n");
return;
    }
memset(vis, false, sizeof(vis));
toposort(0);
}
目录
相关文章
|
算法
The kth great number(小根堆思想,模板题)
The kth great number(小根堆思想,模板题)
55 0
UVa10776 - Determine The Combination(有重复元素的组合问题)
UVa10776 - Determine The Combination(有重复元素的组合问题)
50 0
UVa11157 - Dynamic Frog(动态规划)
UVa11157 - Dynamic Frog(动态规划)
65 0
UVa10596 - Morning Walk(并查集)
UVa10596 - Morning Walk(并查集)
65 0
UVa11710 - Expensive subway(最小生成树)
UVa11710 - Expensive subway(最小生成树)
52 0
UVa668 - Parliament(贪心)
UVa668 - Parliament(贪心)
66 0
|
机器学习/深度学习 测试技术
UVA11175 有向图D和E From D to E and Back
UVA11175 有向图D和E From D to E and Back
UVA11175 有向图D和E From D to E and Back
UVA122 树的层次遍历 Trees on the level
UVA122 树的层次遍历 Trees on the level
AtCoder Beginner Contest 216 G - 01Sequence (并查集 贪心 树状数组 差分约束)
AtCoder Beginner Contest 216 G - 01Sequence (并查集 贪心 树状数组 差分约束)
160 0

热门文章

最新文章

下一篇
开通oss服务