uva 200拓扑排序


//

//  main.cpp

//  ceshi

//

//  Created by 戴之阳 on 2016/11/.

//  Copyright © 2016 sky.dai. All rights reserved.

//


//

//  main.cpp

//  ceshi

//

//  Created by 戴之阳 on 2016/11/14.

//  Copyright © 2016 sky.dai. All rights reserved.

//  拓扑排序

//  基于dfskahn

/*DFS

L ← Empty list that will contain the sorted nodes

S ← Set of all nodes with no outgoing edges

     for each node n in S 

    do

       visit(n)

 

 

function visit(node n)

      if n has not been visited yet then

          mark n as visited

     for each node m with an edge from m to n

        do

           visit(m)

        add n to L*/

#include <iostream>

#include <vector>

#include <map>

#include <algorithm>

#include <cstdlib>

#include <cmath>

#include <list>

#include <stack>

#include <cstring>

#include <cstdio>

using namespace std;


int visited[30];

int have_degreeout[30];  //have_degreeIn[i]=1表示未有入度,2代表有入度

vector<char>node_sort;

vector<char>::iterator iter;



vector<char>indegree[30];  //outgoing



//初始化

void initial()

{

    memset(visited,false,sizeof(visited));

    memset(have_degreeout,0,sizeof(have_degreeout));

    node_sort.clear();

}


void dfs(char ch)

{

    if(visited[ch-'A']==true)

        return;

    visited[ch-'A']=true;

    for(int i=0;i<indegree[ch-'A'].size();i++)

    {

        dfs(indegree[ch-'A'][i]);

    }

    node_sort.push_back(ch);

    

}


int main()

{

    int i,j;

    initial();

    string str1,str2;

    cin>>str1;

    while(cin>>str2 && str2!="#")

    {

        int len ;

        if(str1.size()>str2.size())

            len = str2.size();

        else len = str1.size();

        for(i=0;i<len;i++)

        {

            if(have_degreeout[str1[i]-'A']==0)

                have_degreeout[str1[i]-'A']=1;

            if(have_degreeout[str2[i]-'A']==0)

                have_degreeout[str2[i]-'A']=1;

            if(str2[i]!=str1[i])

            {

                have_degreeout[str1[i]-'A'] = 2;//有出度

                indegree[str2[i]-'A'].push_back(str1[i]);

                break;

            }

        }

        str1 = str2;

    }

    //得到哪些点有入度并存储进vector

    for(char ch = 'A';ch<='Z';ch++)

    {

        if(have_degreeout[ch-'A']==1)

            dfs(ch);

    }

    //

    for(iter=node_sort.begin();iter!=node_sort.end();iter++)

        printf("%c",*iter);

    printf("\n");

    return 0;

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值