ZOJ 1060 Sorting It All Out(POJ 1094)(关系闭包+计数排序)
2011-04-07 10:41
399 查看
这题原来是按拓扑排序的思路走的,因为思维定势的缘故,看到题目的 input 就想到拓扑排序了,后来听路竹说,他第一眼看到题目,想到的是关系闭包,自己好好想想,的确是啊,关系闭包更新邻接矩阵后,不仅可以判环,而且只要加个计数排序,那么序列就直接出来了,这个比用拓扑排序方便的多啊。
哎,重要的是思想,谨记,谨记……
哎,重要的是思想,谨记,谨记……
#include<stdio.h> #include<string.h> #include<stdlib.h> #define N 30 struct node { int id,in; }p ; int cmp(const void *a,const void *b) { struct node *aa=(struct node *)a; struct node *bb=(struct node *)b; return aa->in > bb->in?1:-1; } int map ,n; void floyd() { int i,j,k; for(k=0;k<n;k++) { for(i=0;i<n;i++) for(j=0;j<n;j++) map[i][j]=map[i][j]||map[i][k]&&map[k][j]; } } int f_huan() { int i; for(i=0;i<n;i++) if(map[i][i]) return 1; return 0; } int f_xu() { int i,j; for(i=0;i<n;i++) p[i].id=i,p[i].in=0; for(j=0;j<n;j++) { for(i=0;i<n;i++) if(map[i][j]) p[j].in++; } qsort(p,n,sizeof(p[0]),cmp); for(i=0;i<n-1;i++) if(p[i].in==p[i+1].in) return 0; return 1; } int main() { int i,m,huan,xu,phuan,pxu; char str[4]; while(scanf("%d%d",&n,&m),n+m) { memset(map,0,sizeof(map)); huan=xu=phuan=pxu=0; for(i=1;i<=m;i++) { scanf("%s",str); map[str[0]-'A'][str[2]-'A']=1; floyd(); if(huan)continue; if(xu)continue; huan=f_huan(); //1表示有环 if(huan){phuan=i;continue;} xu=f_xu(); //1表示完成排序 if(xu)pxu=i; } if(huan) printf("Inconsistency found after %d relations",phuan); else if(xu) { printf("Sorted sequence determined after %d relations: ",pxu); for(i=0;i<n;i++) printf("%c",'A'+p[i].id); } else printf("Sorted sequence cannot be determined"); puts("."); } return 0; }
相关文章推荐
- zoj 1060 && poj 1094 Sorting It All Out
- ZOJ 1060 poj 1094 Sorting It All Out(拓扑排序或 弗洛德)
- ZOJ 1060 (POJ 1094) Sorting It …
- ZOJ 1060 poj 1094 Sorting It All Out(拓扑排序或 弗洛德)
- JOJ 1089 & ZOJ 1060 & poj 1094 Sorting It All Out (邻接表的栈拓扑排序模板)
- zoj 1060 || poj 1094 Sorting It All Out(拓扑排序)
- POJ 1094 && ZOJ 1060 Sorting It All Out 【拓扑排序入门】
- POJ 1094 && ZOJ 1060 Sorting It All Out 【拓扑排序入门】
- poj 1094 Sorting It All Out(图论)
- POJ-1094 Sorting It All Out -----拓扑排序判断状态
- poj 1094 Sorting It All Out
- POJ-1094 Sorting It All Out
- POJ 1094 Sorting It All Out
- Sorting It All Out(POJ--1094
- poj 1094 Sorting It All Out(图论)
- poj1094 Sorting It All Out
- ZOJ 1060 Sorting It All Out (POJ1094) (拓扑排序)
- POJ 1094 Sorting It All Out
- poj1094 Sorting It All Out
- poj 1094 Sorting It All Out