LightOJ 1210 Efficient Traffic System

求强联通分量,缩点后分别统计出度和入度为0的点,较大者为答案。

/*
 * Author: stormdpzh
 * Created Time: 2012/7/25 14:11:49
 * File Name: ee.cpp
 */
#include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
#include <functional>

#define sz(v) ((int)(v).size())
#define rep(i, n) for(int i = 0; i < n; i++)
#define repf(i, a, b) for(int i = a; i <= b; i++)
#define repd(i, a, b) for(int i = a; i >= b; i--)
#define out(n) printf("%d\n", n)
#define mset(a, b) memset(a, b, sizeof(a))
#define wh(n) while(1 == scanf("%d", &n))
#define whz(n) while(1 == scanf("%d", &n) && n != 0)
#define lint long long

using namespace std;

const int V = 20005;

vector<int> vec[V];
int id[V], pre[V], low[V], s[V], stop, cnt, scnt;
int n, m;
vector<int> tmp[V];
bool vis[V];
int ind[V], outd[V];

void tarjan(int v, int n)
{
    int t, minc = low[v] = pre[v] = cnt++;
    vector<int>::iterator pv;
    s[stop++] = v;
    for(pv = vec[v].begin(); pv != vec[v].end(); ++pv) {
        if(-1 == pre[*pv]) tarjan(*pv, n);
        if(low[*pv] < minc) minc=low[*pv];
    }
    if(minc < low[v]) {
        low[v] = minc; return;
    }
    do {
        id[t = s[--stop]] = scnt; low[t] = n;
    } while(t != v);
    ++scnt; 
}

void dfs(int u)
{
    vis[u] =true;
    for(int i = 0; i < sz(vec[u]); i++) {
        int v = vec[u][i];
        if(id[v] != id[u]) {
            outd[id[u]]++;
            ind[id[v]]++;
        }
        if(!vis[v]) {
            dfs(v);
        }
    }
}

int main()
{
    int ca = 1;
    int t;
    wh(t) {
        while(t--) {
            scanf("%d%d", &n, &m);
            printf("Case %d: ", ca++);
            for(int i = 0; i < n; i++) vec[i].clear();
            for(int i = 0; i < m; i++) {
                int a, b;
                scanf("%d%d", &a, &b);
                vec[a - 1].push_back(b - 1);
            }
            if(n <= 1) {
                printf("0\n"); 
                continue;
            }
            mset(pre, -1);
            stop = cnt = scnt = 0;
            for(int i = 0; i < n; i++) {
                if(pre[i] == -1) tarjan(i, n);
            }
            mset(vis, false);
            mset(ind, 0);
            mset(outd, 0);
            for(int i = 0; i < n; i++) if(!vis[i])
                dfs(i);
            int res = 0;
            int in = 0, out = 0;
            if(scnt == 1) res = 0;
            else {
                for(int i = 0; i < scnt; i++) {
                    if(!outd[i]) out++;
                    if(!ind[i]) in++;
                }
                res = max(out, in);
            }
            printf("%d\n", res);
        }
    }    
    return 0;
}


你可能感兴趣的:(LightOJ 1210 Efficient Traffic System)