pku2762(Going from u to v or from v to u?)

/*
 * File:   pku2762.cpp,判断是否为若联通图,缩点后构建新图,对新图进行拓扑排序,
 * 如果拓扑序列唯一,则为若联通图
 * Author: chenjiang
 *
 * Created on 2010年5月8日, 下午4:05
 */

#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
#define _max 1001
vector<int>v1[_max];
vector<int>v2[_max];
vector<int>v3[_max];
bool visited[_max];
int scc_id[_max];
int order[_max];
int indegree[_max];
int n, m;
int id;
int ind;

void dfs1(int k) {
    int i;
    visited[k] = 1;
    for (i = 0; i < v1[k].size(); i++) {
        if (!visited[v1[k][i]])
            dfs1(v1[k][i]);
    }
    ind++;
    order[ind] = k;
}

void dfs2(int k) {
    int i;
    visited[k] = 1;
    scc_id[k] = id;
    for (i = 0; i < v2[k].size(); i++) {
        if (!visited[v2[k][i]])
            dfs2(v2[k][i]);
    }
}

void kosaroju() {
    int i;
    ind = 0;
    memset(visited, 0, sizeof (visited));
    for (i = 1; i <= n; i++) {
        if (!visited[i])
            dfs1(i);
    }

    memset(visited, 0, sizeof (visited));
    id = 0;
    for (i = ind; i >= 1; i--) {
        if (!visited[order[i]]) {
            id++;
            dfs2(order[i]);
        }
    }
}

bool top_sort() {//判断拓扑序列是否唯一
    int i,j;
    int k;
    int num=0;
    for(i=1;i<=id;i++)
    {
        num=0;
        for(j=1;j<=id;j++)
        {
            if(indegree[j]==0)
            {
                k=j;
                num++;
            }
        }
        //if(num==0)return 0;
        if(num>1)return 0;
        indegree[k]=-1;
        for(j=0;j<v3[k].size();j++)
        {
            indegree[v3[k][j]]--;
        }
    }
    return 1;
}

/*
 *
 */
int main(int argc, char** argv) {

    int i, j, a, b;
    int t;
    //freopen("a.a", "r", stdin);
    cin >> t;
    while (t--) {
        cin >> n >> m;
        for (i = 1; i <= n; i++) {
            v1[i].clear();
            v2[i].clear();
            v3[i].clear();
        }
        for (i = 1; i <= m; i++) {
            cin >> a >> b;
            v1[a].push_back(b);
            v2[b].push_back(a);
        }
        kosaroju();/*
        cout << id << endl;
        for (i = 1; i <= n; i++) {
            printf("scc_id[%d]=%d/n", i, scc_id[i]);
        }*/
        memset(indegree, 0, sizeof (indegree));
        for (i = 1; i <= n; i++) {
            for (j = 0; j < v1[i].size(); j++) {
                if (scc_id[i] != scc_id[v1[i][j]]) {
                    v3[scc_id[i]].push_back(scc_id[v1[i][j]]);
                    indegree[scc_id[v1[i][j]]]++;
                }
            }
        }/*
        for (i = 1; i <= id; i++) {
            printf("indegree[%d]=%d/n", i, indegree[i]);
        }*/
        int ans = top_sort();//cout<<"top_sort over"<<endl;
        if (ans)cout << "Yes" << endl;
        else cout << "No" << endl;
        //system("pause");
    }
    return (EXIT_SUCCESS);
}

阅读更多
文章标签: file 2010
个人分类: ACM
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭