zoukankan      html  css  js  c++  java
  • 每日一算法之拓扑排序

    伪代码:

    TopLogical(G)
        call DFS to compute finishtime
        as each vertex finished , insert it onto the front of a linked list
      return the linked list of vertices
    

      

    实现如下:

    #include <iostream>
    #include <vector>
    #include <memory>
    using namespace std;
    vector<vector<int>> graphic;
    vector<int> res;
    bool *visit;
    int length;
    void init()
    {
    	visit = new bool[length];
    	cout<<"init:"<<length<<endl;
    	for(int i = 0 ; i < length ; ++i)
    	{
    		visit[i] = false;
    	}
    }
    void Dfs(int cur)
    {
    	if(visit[cur] )
    	{
    		return ;
    	}
    	visit[cur] = true;
    	for(int i = 0 ; i < graphic[cur].size() ; ++i)
    	{
    	
    		Dfs(graphic[cur][i]);
    	}
    	cout<<"dfs:"<<cur<<endl;
    	res.push_back(cur);
    }
    ///void SecondDfs()
    //{
    
    //}
    int main()
    {
    	length = 7;
    	vector<int> ve;
    	init();
    	for(int i = 0 ; i < length ; ++i)
    	{
    		graphic.push_back(ve);
    	}
    	graphic[0].push_back(1);
    	graphic[0].push_back(3);
    	graphic[1].push_back(2);
    	graphic[1].push_back(3);
    	graphic[2].push_back(6);
    	graphic[4].push_back(2);
    	graphic[4].push_back(5);
    	graphic[5].push_back(6);
    	for(int i = 0 ; i < length ; ++i)
    	{
    		Dfs(i);
    	}
    	for(int i = res.size()-1 ; i >= 0; --i)
    	{
    		cout<<res[i]<<" ";
    	}
    
    
    	return 0;
    }
    

      

  • 相关阅读:
    用脚本实现对pm2.5 数据的获取
    虚拟机下的快盘空间分配方案
    C++中new的用法
    只在堆或栈上生成对象
    Virtualbox识别USB设备
    最长公共字序列
    gdb 打印vector 等stl数据
    LC_CTYPE: cannot change locale
    字符串压缩
    对象的概念
  • 原文地址:https://www.cnblogs.com/fengyuehan/p/4649702.html
Copyright © 2011-2022 走看看