zoukankan      html  css  js  c++  java
  • Uva(10305)

    这是一道关于拓扑排序的题,并且要输出其中一种拓扑序列
    #include<stdio.h>
    #include<string.h>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    const int maxn=150;
    int c[maxn];
    int topo[maxn],t;
    int G[maxn][maxn];
    int n,m;
    bool dfs(int u)
    {
    	c[u]=-1;
    	for(int v=1;v<=n;v++)
    	{
    		if(G[u][v])
    		{
    			if(c[v]<0) return false;
    			else if(!c[v]&&!dfs(v))
    			return false;
    		}
    	}
    	c[u]=1;topo[--t]=u;
    	return true;
    } 
    //用数组c来表示节点访问的状态,其中c[u]=0表示未访问过,c[u]=-1表示正在访问,c[u]=1表示已经访问过且他的子孙都已经访问过
    bool toposort()
    {
    	t=n;
    	memset(c,0,sizeof(c));
    	for(int u=1;u<=n;u++)
    	{
    		if(!c[u])
    		{
    			if(!dfs(u))
    			return false;
    		}
    	}
    	return true;
    }
    int main()
    {
    	while(scanf("%d %d",&n,&m)!=EOF)
    	{
    		if(n==0&&m==0)
    		break;
    		memset(G,0,sizeof(G));
    		memset(topo,0,sizeof(topo));
    		int u,v;
    		for(int i=0;i<m;i++)
    		{
    			scanf("%d %d",&u,&v);
    			G[u][v]=1;
    		}
    		toposort();
    		for(int i=0;i<n-1;i++)
    		printf("%d ",topo[i]);
    		printf("%d
    ",topo[n-1]);
    	}
    	return 0;
    } 
    

      

  • 相关阅读:
    struts总结
    struts的MVC详细实现
    struts的由来
    Hibernate的搭建及使用
    Hibernate简介
    泛型
    eclipse手动添加源码
    beanUtils操作bean的属性
    ref:JAVA之Forward和Redirect的区别
    ref:下一个项目为什么要用 SLF4J
  • 原文地址:https://www.cnblogs.com/NaCl/p/9580155.html
Copyright © 2011-2022 走看看