标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 4885 | Accepted: 1973 |
Description
Input
Output
Sample Input
a b f g a b b f v w x y z v y x v z v w v
Sample Output
abfg abgf agbf gabf wxzvy wzxvy xwzvy xzwvy zwxvy zxwvy
Source
L← Empty list that will contain the sorted elements S ← Set of all nodes with no incoming edges while S is non-empty do remove a node n from S insert n into L foreach node m with an edge e from nto m do remove edge e from thegraph ifm has no other incoming edges then insert m into S if graph has edges then return error (graph has at least onecycle) else return L (a topologically sortedorder)
就是找入度为0的点(最好用个stack,循环的话复杂的太高),加入topo头部
感觉比dfs好,复杂度都是O(V+E)
本题回溯所有方案,复杂度乘上一个V;V很小,不用stack也可以;用个id比较方便吧
字符读入太坑人.........
// // main.cpp // poj1270 // // Created by Candy on 9/11/16. // #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int N=30,M=55; char s[105]; int a[N],num=0,n=0,id[N]; int ch[N][N],topo[N],ind[N]; void print(){ for(int i=1;i<=n;i++) printf("%c",(char)topo[i]+‘a‘-1); printf("\n"); } void dfs(int d){ //printf("dfs %d\n",d); if(d==n+1){print();return;} for(int i=1;i<=n;i++) if(ind[i]==0){ ind[i]--; topo[d]=a[i]; for(int j=1;j<=ch[i][0];j++) ind[ch[i][j]]--; dfs(d+1); for(int j=1;j<=ch[i][0];j++) ind[ch[i][j]]++; ind[i]++; } } int main(int argc, const char * argv[]) { while(fgets(s,105,stdin)){ //printf("p %s\n",s); n=0; memset(topo,0,sizeof(topo)); memset(ch,0,sizeof(ch)); memset(ind,0,sizeof(ind)); int len=strlen(s); //printf("len %d\n",len); for(int i=0;i<len;i++) if(s[i]>=‘a‘&&s[i]<=‘z‘) a[++n]=s[i]-‘a‘+1; sort(a+1,a+1+n); for(int i=1;i<=n;i++) id[a[i]]=i; fgets(s,105,stdin); len=strlen(s); int last=0; for(int i=0;i<=len;i++) if(s[i]>=‘a‘&&s[i]<=‘z‘){ int t=s[i]-‘a‘+1; t=id[t]; if(last==0) last=t; else{ch[last][++ch[last][0]]=t;ind[t]++;last=0;} } dfs(1); printf("\n"); } return 0; }
POJ1270 Following Orders[拓扑排序所有方案 Kahn]
标签:
原文地址:http://www.cnblogs.com/candy99/p/5863074.html