思路是老师上课讲的。
先找入度为0的点,然后删去该点以及从该点出去的边,然后再找入度为0的点,直到找不到为止:
WA了3次主要是因为把序号为1 的点当作了第一个入度为0的点。这在题目中是没有描述的,所以第一个也得找。
代码如下:
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 100+10;
int topo[maxn][maxn], visit[maxn], m, n, flag=0;
int init()//输入边
{
for(int i = 0; i < n; i++)
{
int a, b;
cin>>a>>b;
if(a!=b)
topo[a][b] = 1;
}
return 0;
}
int returnx()
{
int count;
for(int i = 1;i <= m; i++)
{
count = 0;
if(visit[i]) continue;
for(int j = 1; j <= m; j++)
if(topo[j][i])count++;
if(count==0)return i;
}
return 0;
}
int Topo(int u)
{
visit[u] = 1;
if(flag)cout<<" ";
cout<<u;
for(int i = 1;i <= m; i++)
topo[u][i] = 0;
flag = 1;
return 0;
}
int main ()
{
int temp;
while(cin>>m>>n)
{
if(!m&&!n)break;
memset(visit, 0, sizeof(visit));
memset(topo, 0, sizeof(topo));
init();
flag=0;
while((temp = returnx()))//找入度为0的点
Topo(temp);//处理该点
cout<<endl;
}
return 0;
}