SDNU1089拓扑排序(有向图的存储)

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+10;
int dp[maxn][maxn];
bool vis[maxn];
queue<int>que;
int n,m,a,b;
bool judge(int x)
{
    for(int i=1; i<=n; ++i)
        if(dp[i][x]==1)
            return false;
    return true;
}
void clears(int x)
{
    for(int i=1; i<=n; ++i)
        dp[x][i]=0;
}
void solve()
{
    bool flag=1;
    int t=n;
    while(t--)
    {
        for(int i=1; i<=n; ++i)
            if(!vis[i]&&judge(i))
            {
                vis[i]=1;
                clears(i);
                flag=0;
                que.push(i);
                break;
            }
    }
    if(flag||que.size()<n)
        printf("IMPOSABLE\n");
    else
    {
        while(!que.empty())
        {
            printf("%d",que.front());
            que.pop();
            if(!que.empty())
                printf(" ");
            else
                printf("\n");
        }
    }
}
int main()
{
    memset(dp,0,sizeof(dp));
    memset(vis,0,sizeof(vis));
    scanf("%d%d",&n,&m);
    for(int i=0; i<m; ++i)
    {
        scanf("%d%d",&a,&b);
        dp[a][b]=1;
    }
    solve();
    return 0;
}
/**
5 4
1 2
2 1
3 4
4 3
---
5 4
1 1
1 2
2 1
2 2
**/

猜你喜欢

转载自blog.csdn.net/qq_41658955/article/details/86882920
今日推荐