标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 20395 Accepted Submission(s): 8197
#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> #include<queue> using namespace std; int map[505][505]; int degree[505],ans[505]; int n,m; struct cmp1{ bool operator ()(int &a,int &b){ return a>b;//最小值优先 } }; /*bool operator<(const int &a,const int &b) { if(a<b) return 1; return 0; }*/ void topusort() { priority_queue<int,vector<int>,cmp1> s; while(!s.empty()) s.pop(); int cnt=0; for(int i=n; i>=1; i--) { if(degree[i]==0) { s.push(i); } } while(!s.empty()) { int h=s.top(); s.pop(); degree[h]--; ans[cnt++]=h; for(int i=n; i>=1; i--) { if(map[h][i]==1) { //map[h][i]=0; degree[i]--; if(degree[i]==0) s.push(i); } } } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { memset(map,0,sizeof(map)); memset(degree,0,sizeof(degree)); memset(ans,0,sizeof(ans)); for(int i=0; i<m; i++) { int x,y; scanf("%d%d",&x,&y); if(map[x][y]==0) { map[x][y]=1; degree[y]+=1; } } //cout<<degree[3]<<endl; topusort(); for(int i=0;i<n;i++) { if(i==n-1) printf("%d\n",ans[i]); else printf("%d ",ans[i]); } } return 0; }
再附上第一次做时模拟的代码:
#include<iostream> #include<cstdio> #include<string.h> using namespace std; int sf[510][510],zt[510]; int main() { int n,m,p1,p2; while(scanf("%d%d",&n,&m)!=EOF) { memset(sf,0,sizeof(sf)); memset(zt,0,sizeof(zt)); while(m--) { scanf("%d%d",&p1,&p2); if(!sf[p1][p2]) { sf[p1][p2]=1; zt[p2]++; } } int i,j,k; for(i=1; i<=n; i++) for(j=1; j<=n; j++) if(zt[j]==0) { zt[j]--; if(i==n) printf("%d\n",j); else printf("%d ",j); for(k=1;k<=n;k++) if(sf[j][k]) zt[k]--; break; } } return 0; }
标签:
原文地址:http://www.cnblogs.com/jasonlixuetao/p/5500608.html