/*
题意: 给N个比赛结果,输出拓扑排名
YY:拓扑排序,初搞,最近练邻接表,感觉比邻接矩阵快的多
两个都写了一下,竟差两倍之多,邻接表神物啊!!!
*/
//邻接表 Accepted 1285 15MS 248K 1030 B C++ kfinder
#include <iostream>
using namespace std;
int ind[505]; // indegree入度个数
int adj[250010]; //adjacency list邻接表位置值
int adj_next[250010];//邻接表下一指针
int tail[505]; //邻接表尾
int main()
{
int n,m,i,j,a,b;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i = 0; i <= n; i++) {
tail[i] = -1;
adj[i] = -1;
adj_next[i] = -1;
ind[i] = 0;
}
for(i = 0; i < m; ++i)
{
scanf("%d%d",&a,&b);
int x = tail[a],flag = 0;
while(x != -1) //判断是否重边
{
if(adj[x] == b){
flag = 1;
break;
}
x = adj_next[x];
}
if(!flag)//关联a的邻接表
{
adj[i] = b;
adj_next[i] = tail[a];
tail[a] = i;
ind[b] ++;
}
}
for(i = 1;i <= n; i++)//找n次
{
for(j = 1;j <= n;j++)//遍历
{
if(ind[j] == 0){//当入度为0时,说明靠前
ind[j] = -1;//在下次寻找入度为0时跳过
//
if(i == 1) printf("%d",j);
else printf(" %d",j);
//
for(int k = tail[j]; k != -1; k = adj_next[k])//邻接位置入度减一
{
ind[adj[k]] --;
}
break;
}
}
}
printf("\n");
}
return 0;
}
//邻接矩阵 Accepted 1285 31MS 1232K 759 B C++ kfinder
#include <iostream>
using namespace std;
int map[505][505];
int indegree[505];
int n,m;
int main()
{
int i,a,b;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(map,0,sizeof(map));
memset(indegree,0,sizeof(indegree));
for(i = 0;i < m; i++)
{
scanf("%d %d",&a,&b);
if(!map[a][b])
{
map[a][b] = 1;
indegree[b]++;
}
}
for(i = 1;i <= n; i++)
{
for(int j = 1;j <= n; j++)
{
if(indegree[j] == 0){
indegree[j] = -1;
//
if(i == 1) printf("%d",j);
else printf(" %d",j);
//
for(int k = 1;k <= n; k++)
{
if(map[j][k] == 1){
map[j][k] = 0;
indegree[k] --;
}
}
break;
}
}
}
printf("\n");
}
return 0;
}