POJ 1094

Thinking in topological sort

how to judge if has a loop

when there are still some unvisited node, but the number of node whose in-degree==0 equals zero, we can say: there is a loop in the graph.
(因为拓扑排序是一个节点一个节点的去排除,当有未排除的节点时,并且没有入读不为0的节点,那么就一定有环存在)

how to judge if has isolated node or is the top-order not exclusive

when the are still some unvisited nodes, but the number of node whose in-degree == 0 greater than one, we can say the order is uncertain.

talk is cheap, show me the code.

#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <queue>
#include <cstring>
#include <cstdio>
#include <map>
#include <assert.h>

using namespace std;
const int MAXSIZE = 30;
int road[MAXSIZE][MAXSIZE];
int indegree[MAXSIZE];
int visit[MAXSIZE];
int temp[MAXSIZE];
int n,m;
string string1;
int topsort() {
    memset(visit, 0, sizeof(visit));
    memcpy(temp, indegree, sizeof(indegree));
    string1 = "";
    int flag = 1;
    for (int i = 0; i < n; ++i) {
        int m = 0, u = -1;
        for (int j = 0; j < n; ++j) {
            if (!visit[j] && temp[j] == 0) {
                u = j, m++;
            }
        }
        if (m == 0) return 0; //有环路
        if (m > 1) flag =  -1; //无序
        visit[u] = 1;
        string1 += (u+'A');
        for (int j = 0; j < n; ++j) {
            if (!visit[j] && road[u][j])
                temp[j]--;
        }
    }
    return flag;
}
int main(){
//    freopen("../in.txt", "r", stdin);
    while (scanf("%d %d", &n, &m)&&n){
        memset(road, 0, sizeof(road));
        memset(indegree, 0, sizeof(indegree));
        char a,op,b;
        bool isok = false;

        for (int k = 0; k < m; ++k) {
            cin>>a>>op>>b;
            road[a-'A'][b-'A'] = 1;
            if (isok) continue;
            //入度
            memset(indegree,0, sizeof(indegree));
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < n; ++j) {
                    indegree[j]+= road[i][j];
                }
            }
            int res = topsort();
            if (res == 0){
                cout<<"Inconsistency found after "<<k+1<<" relations."<<endl;
                isok = true;
            } else if (res == 1){
                cout<<"Sorted sequence determined after "<<k+1<<" relations: "<<string1<<"."<<endl;
                isok = true;
            }
        }
        if (!isok)
            cout<<"Sorted sequence cannot be determined."<<endl;
    }
}

Reference

https://www.cnblogs.com/yueshuqiao/archive/2011/08/16/2140485.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值