4 3 1 2 2 3 4 3
1 2 4 3
#include<iostream>
#include<queue>
#include<algorithm>
#include<string.h>
#include<stdio.h>
using namespace std;
const int M=505;
int graph[M][M];
int digree[M];
int main()
{
int n,m;
while(cin>>n>>m)
{
memset(graph,0,sizeof(graph));
memset(digree,0,sizeof(digree));
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
if(graph[a][b]==0)
{
graph[a][b]=1;
digree[b]++;
}
}
priority_queue<int , vector<int>,greater<int> >q;
for(int k=1;k<=n;k++)
{
if(!digree[k])
q.push(k);
}
int ok=1;
while(!q.empty())
{
int cur=q.top();
if(ok)
{
cout<<cur;ok=0;
}
else
cout<<" "<<cur;
q.pop();
for(int j=1;j<=n;j++)
{
if(graph[cur][j])
{
digree[j]--;
if(digree[j]==0)
q.push(j);
}
}
}
cout<<endl;
}
return 0;
}
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
int graph[500][500];
int digree[500];
int main()
{
int n,m;
while(cin>>n>>m,n+m)
{
memset(graph,0,sizeof(graph));
memset(digree,0,sizeof(digree));
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
if(!graph[a][b])
{
graph[a][b]=1;
digree[b]++;
}
}
queue<int>q;
for(int j=1;j<=n;j++)
{
if(digree[j]==0)
q.push(j);
}
while(!q.empty())
{
int cur=q.front();
cout<<cur<<" ";
q.pop();
for(int k=1;k<=n;k++)
{
if(graph[cur][k])
{
digree[k]--;
if(digree[k]==0)
q.push(k);
}
}
}
cout<<endl;
}
}
原文地址:http://blog.csdn.net/lsgqjh/article/details/45955885