天天看點

UVA 315 Network (tarjan cut)

題意:

求連通圖中割點的個數

分析:

模版題

代碼:

//
//  Created by TaoSama on 2015-11-21
//  Copyright (c) 2015 TaoSama. All rights reserved.
//
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>

using namespace std;
#define pr(x) cout << #x << " = " << x << "  "
#define prln(x) cout << #x << " = " << x << endl
const int N =  + , INF = , MOD =  + ;
const int M = N * N;

int n;

struct Edge {
    int v, nxt;
} edge[M];
int head[N], cnt;

void addEdge(int u, int v) {
    edge[cnt] = (Edge) {v, head[u]};
    head[u] = cnt++;
    edge[cnt] = (Edge) {u, head[v]};
    head[v] = cnt++;
}

int dfn[N], low[N], cut[N], dfsNum;

void tarjan(int u, int f) {
    dfn[u] = low[u] = ++dfsNum;
    int son = ;
    for(int i = head[u]; ~i; i = edge[i].nxt) {
        int v = edge[i].v;
        if(v == f) continue;
        if(!dfn[v]) {
            ++son;
            tarjan(v, u);
            low[u] = min(low[u], low[v]);
            if(low[v] >= dfn[u]) cut[u] = true;
        } else low[u] = min(low[u], dfn[v]);
    }
    if(f <  && son == ) cut[u] = false;
}

void init() {
    dfsNum = ;
    memset(dfn, , sizeof dfn);
    memset(cut, false, sizeof cut);
}

int main() {
#ifdef LOCAL
    freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
//  freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
    ios_base::sync_with_stdio();

    while(scanf("%d", &n) ==  && n) {
        cnt = ; memset(head, -, sizeof head);
        int u, v;
        while(scanf("%d", &u) && u) {
            while(getchar() != '\n') {
                scanf("%d", &v);
                addEdge(u, v);
            }
        }
        init();
        tarjan(, -);
        int ans = ;
        for(int i = ; i <= n; ++i) ans += cut[i];
        printf("%d\n", ans);
    }
    return ;
}