题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1285
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<stack>
#include<fstream>
#include<queue>
#include<string.h>
#include<list>
#include<map>
using namespace std;
const int maxnum = 501;
bool graph[maxnum][maxnum];
int in[maxnum];
struct cmp
{
bool operator()(int a, int b)
{
return a > b;
}
};
int main()
{
int n, m;
while (cin >> n >> m)
{
memset(graph, false, sizeof(graph));
memset(in, 0, sizeof(in));
for (int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
if (graph[x][y])
continue;
graph[x][y] = true;
in[y]++;
}
priority_queue<int, vector<int>, cmp> myque;
for (int i = 1; i <= n; i++)
{
if (in[i] == 0)
myque.push(i);
}
int cnt = 0;
while (!myque.empty())
{
int tmptop = myque.top();
cnt++;
if (cnt != n)
cout << tmptop << " ";
else cout << tmptop << endl;
myque.pop();
in[tmptop] = -1;
for (int i = 1; i <= n; i++)
{
if (graph[tmptop][i])
{
in[i]--;
if (in[i] == 0)
myque.push(i);
}
}
}
}
return 0;
}
/*
5 3
1 4
4 3
2 5
1 2 4 3 5
*/
原文:http://www.cnblogs.com/wuxiangli/p/6397250.html