Ordering Tasks UVA - 10305 DFS拓扑排序

理解:一道DFS的水题,平常写的有显示的入度出度表示,而这个的刘汝佳的代码没有用显示表示,而是用DFS形成类似树的结构,不同枝的顺序可以任意 而在toposort里面没有用到的点再进行DFS则是把没有用到的点作为新树的根,其中,把当前结点加入拓扑排序的首部(线性序列的当前第一个位置,随着排序的进行,这个位置会不断前移)很关键  其实这种方法就是把入度出度隐藏起来了



#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
int vis[maxn];
int topo[maxn];
int mp[maxn][maxn];
int n,m;
int t;
bool dfs(int x){
vis[x]=-1;
for(int i=1;i<=n;i++){
    if(mp[x][i]){
        if(vis[i]==-1)return 0;
       else  if(!vis[i])dfs(i);
    }
}
vis[x]=1;
topo[t--]=x;//这里相当于把没有入度的放在最前面
return 1;

}
bool toposort(){
t=n;
for(int i=1;i<=n;i++){
    if(!vis[i]){
        if(!dfs(i))return 0;  //没有用到的入度肯定小于等于之前用到的点,所以在DFS中topo[t--]被放在前面
    }
}
return 1;

}
int main(){
while(cin>>n>>m&&n){
        memset(mp,0,sizeof(mp));
memset(vis,0,sizeof(vis));
    t=n;
    int u,v;
    for(int i=1;i<=m;i++){
        cin>>u>>v;
        mp[u][v]=1;
    }
   if(toposort()){
    printf("%d",topo[1]);
    for(int i=2;i<=n;i++){
        printf(" %d",topo[i]);
    }
    printf("\n");
   }
}
return 0;
}

猜你喜欢

转载自blog.csdn.net/bug___maker/article/details/81053459