标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 17915 Accepted Submission(s): 7169
#include <bits/stdc++.h> using namespace std; const int N(500+5); vector<int> g[N]; bool vis[N]; int topo[N], tot; void dfs(int u){ vis[u]=1; for(int i=0; i<g[u].size(); i++){ int &v=g[u][i]; if(vis[v]) continue; dfs(v); } topo[--tot]=u; } int main(){ for(int n, m; ~scanf("%d%d", &n, &m);){ for(int i=1; i<=n; i++) g[i].clear(); for(int u, v; m--;) scanf("%d%d", &u, &v), g[u].push_back(v); for(int i=1; i<=n; i++) sort(g[i].begin(), g[i].end(), greater<int>()); memset(vis, 0, sizeof(vis)); tot=n; for(int i=n; i; i--) if(!vis[i]) dfs(i); printf("%d", topo[0]); for(int i=1; i<n; i++) printf(" %d", topo[i]); puts(""); } }
#include <bits/stdc++.h> using namespace std; const int N(500+5); vector<int> g[N]; int in[N]; int main(){ for(int n, m; ~scanf("%d%d", &n, &m);){ for(int i=1; i<=n; i++) g[i].clear(); memset(in, 0, sizeof(in)); for(int u, v; m--;) scanf("%d%d", &u, &v), g[u].push_back(v), in[v]++; for(int i=0; i<n; ) for(int u=1; u<=n; u++){ if(in[u]==0){ if(!i++) printf("%d", u); else printf(" %d", u); in[u]=-1; for(int j=0; j<g[u].size(); j++){ int &v=g[u][j]; in[v]--; } break; } } puts(""); } }
#include <bits/stdc++.h> using namespace std; const int N(500+5); vector<int> g[N]; int in[N]; typedef pair<int,int> P; priority_queue<P, vector<P>, greater<P> > que; int main(){ for(int n, m; ~scanf("%d%d", &n, &m);){ for(int i=1; i<=n; i++) g[i].clear(); memset(in, 0, sizeof(in)); for(int u, v; m--;) scanf("%d%d", &u, &v), g[u].push_back(v), in[v]++; for(int i=1; i<=n; i++) que.push({in[i], i}); bool first=true; while(!que.empty()){ P top=que.top(); que.pop(); int &u=top.second; if(in[u]!=top.first) continue; if(first) printf("%d", u), first=false; else printf(" %d", u); for(int i=0; i<g[u].size(); i++){ int &v=g[u][i]; que.push({--in[v], v}); } } puts(""); } }
标签:
原文地址:http://www.cnblogs.com/Patt/p/4816479.html