4 3 1 2 2 3 4 3
1 2 4 3
#include<map>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<cctype>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
const int maxv = 500 + 5;
int N,M;
int p,q,index;
int degree[maxv];
int sortGraph[maxv];
bool graph[maxv][maxv];
void init(){
index=0;
memset(graph,false,sizeof(graph));
memset(degree,0,sizeof(degree));
}
void topSort(){
for(int i=1;i<=N;i++){
for(int u=1;u<=N;u++){
if(degree[u]==0){
degree[u]=-1;
sortGraph[index++]=u;
for(int v=1;v<=N;v++){
if(graph[u][v]) degree[v]--;
}break; //保证题意输出顺序
}
}
}
for(int i=0;i<index;i++){
if(i==index-1) printf("%d\n",sortGraph[i]);
else printf("%d ",sortGraph[i]);
}
}
int main(){
while(scanf("%d%d",&N,&M)!=EOF){
init();
for(int i=0;i<M;i++){
scanf("%d%d",&p,&q);
if(!graph[p][q]){
graph[p][q]=true;
degree[q]++;
}
}
topSort();
}return 0;
}
#include<map>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<cctype>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
const int maxv = 500 + 5;
int N,M;
int p,q,index;
int degree[maxv];
int sortGraph[maxv];
bool graph[maxv][maxv];
void init(){
index=0;
memset(graph,false,sizeof(graph));
memset(degree,0,sizeof(degree));
}
void topSort(){
priority_queue<int,vector<int>,greater<int> >que;
while(!que.empty()) que.pop();
for(int i=1;i<=N;i++){
if(degree[i]==0)
que.push(i);
}
while(!que.empty()){
int u=que.top(); que.pop();
sortGraph[index++]=u;
for(int v=1;v<=N;v++){
if(graph[u][v]){
degree[v]--;
if(degree[v]==0) que.push(v);
}
}
}
for(int i=0;i<index;i++){
if(i==index-1) printf("%d\n",sortGraph[i]);
else printf("%d ",sortGraph[i]);
}
}
int main(){
while(scanf("%d%d",&N,&M)!=EOF){
init();
for(int i=0;i<M;i++){
scanf("%d%d",&p,&q);
if(!graph[p][q]){
graph[p][q]=true;
degree[q]++;
}
}
topSort();
}return 0;
}
原文地址:http://blog.csdn.net/jhgkjhg_ugtdk77/article/details/45565643