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);
}
目录
相关文章
|
开发框架 .NET
poj 3468 A Simple Problem with Integers线段树区间修改
题目意思很简单,有N个数,Q个操作, Q l r 表示查询从l到r 的和,C l r v 表示将从l到r 的值加上v,明显的线段树,不知道线段树的人肯定暴力,肯定超时,哈哈!!
33 0
UVa10776 - Determine The Combination(有重复元素的组合问题)
UVa10776 - Determine The Combination(有重复元素的组合问题)
43 0
AtCoder Beginner Contest 216 G - 01Sequence (并查集 贪心 树状数组 差分约束)
AtCoder Beginner Contest 216 G - 01Sequence (并查集 贪心 树状数组 差分约束)
152 0
AtCoder Beginner Contest 216 D - Pair of Balls (思维建图 拓扑排序判断有向图是否有环)
AtCoder Beginner Contest 216 D - Pair of Balls (思维建图 拓扑排序判断有向图是否有环)
125 0
AtCoder Beginner Contest 223 D - Restricted Permutation(建图 思维 构造 拓扑排序)
AtCoder Beginner Contest 223 D - Restricted Permutation(建图 思维 构造 拓扑排序)
130 0
codeforces1253——D. Harmonious Graph(并查集)
codeforces1253——D. Harmonious Graph(并查集)
89 0