您的位置:首页 > 其它

poj 3687 Labeling Balls 【拓扑排序】

2015-09-24 11:17 281 查看
Labeling Balls
Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 12481Accepted: 3584
DescriptionWindy has N balls of distinct weights from 1 unit to N units. Now he tries to label them with 1 to N in such a way that:No two balls share the same label.The labeling satisfies several constrains like "The ball labeled with a is lighter than the one labeled with b".Can you help windy to find a solution?InputThe first line of input is the number of test case. The first line of each test case contains two integers, N (1 ≤ N ≤ 200) and M (0 ≤ M ≤ 40,000). The next M line each contain two integers a and b indicatingthe ball labeled with a must be lighter than the one labeled with b. (1 ≤ a, b ≤ N) There is a blank line before each test case.OutputFor each test case output on a single line the balls' weights from label 1 to label N. If several solutions exist, you should output the one with the smallest weight for label 1, then with the smallest weight for label 2, then with the smallestweight for label 3 and so on... If no solution exists, output -1 instead.Sample Input
5

4 0

4 1
1 1

4 2
1 2
2 1

4 1
2 1

4 1
3 2
Sample Output
1 2 3 4
-1
-1
2 1 3 4
1 3 2 4
分析:
反向建图。
wa代码:
#include<cstdio>#include<cstring>#include<cstdlib>#include<algorithm>#include<queue>using namespace std;int map[250][250];int vis[250];void topo(int n){int i,j,mark,que[250];for(i=n;i>=0;i--){int x=0;for(j=n;j>=0;j--){//x=1;if(vis[j]==0){x=1;mark=j;break;}}if(x==0)break;que[mark]=i;vis[mark]=-1;for(j=1;j<=n;j++){if(map[mark][j])vis[j]--;}}if(i!=-1)printf("-1\n");else{printf("%d",que[1]);for(i=2;i<=n;i++)printf(" %d",que[i]);printf("\n");}}int main(){int t;scanf("%d",&t);while(t--){int n,m,a,b;memset(map,0,sizeof(map));memset(vis,0,sizeof(vis));scanf("%d%d",&n,&m);while(m--){scanf("%d%d",&a,&b);if(!map[b][a])map[b][a]=1;vis[a]++;}topo(n);}return 0;}
ac代码:[/code]
#include<cstdio>#include<cstring>#include<algorithm>#include<cstdlib>#include<queue>using namespace std;int g[210][210];int degree[210];int value[210];priority_queue<int>q;int toposort(int n){int j=n;for(int i=1;i<=n;i++){if(degree[i]==0){q.push(i);}}if(q.empty())return 0;while(!q.empty()){int t=q.top();q.pop();value[t]=j;j--;for(int i=1;i<=n;i++){if(g[i][t]!=0){g[i][t]=0;degree[i]--;if(degree[i]==0)q.push(i);}}}if(j!=0)return 0;return 1;}int main(){int T;int n,m,a,b;scanf("%d",&T);while(T--){memset(g,0,sizeof(g));memset(degree,0,sizeof(degree));scanf("%d%d",&n,&m);while(m--){scanf("%d%d",&a,&b);if(g[a][b]>0)degree[a]--;g[a][b]=1;degree[a]++;}int x=toposort(n);if(x==0)printf("-1\n");else{for(int i=1;i<n;i++)printf("%d ",value[i]);printf("%d\n",value);}}return 0;}
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: