强连通分量 CCF201509-4 高速公路

传送门:点击打开链接

题意:告诉有向图,求互通的城市对数。

思路:强连通分量裸题,求出所有的强连通分量,答案就等于sigma s[i]*(s[i]-1)/2,s[i]是每个强连通分量的大小

#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <Stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <bitset>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
#define fuck(x) cout << "[" << x << "]"
#define FIN freopen("input.txt", "r", stdin)
#define FOUT freopen("output.txt", "w+", stdout)
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;

const int MX = 1e5 + 5;
const int INF = 0x3f3f3f3f;

struct Edge {
    int v, nxt;
} E[MX << 1];
int Head[MX], erear;
void edge_init() {
    erear = 0;
    memset(Head, -1, sizeof(Head));
}
void edge_add(int u, int v) {
    E[erear].v = v;
    E[erear].nxt = Head[u];
    Head[u] = erear++;
}

int Bcnt, Top, Index;
int Low[MX], DFN[MX];
int belong[MX], Stack[MX];
bool inStack[MX];

void Init_tarjan(int n) {
    Bcnt = Top = Index = 0;
    for(int i = 1; i <= n; ++i) Low[i] = DFN[i] = 0;
}
void Tarjan(int u) {
    Stack[Top++] = u;
    inStack[u] = 1;
    Low[u] = DFN[u] = ++Index;
    for(int i = Head[u]; ~i; i = E[i].nxt) {
        int v = E[i].v;
        if(!DFN[v]) {
            Tarjan(v);
            Low[u] = min( Low[v], Low[u]);
        } else if(inStack[v]) {
            Low[u] = min( Low[u], DFN[v]);
        }
    }
    if(Low[u] == DFN[u]) {
        ++Bcnt;
        int v;
        do {
            v = Stack[--Top];
            inStack[v] = 0;
            belong[v] = Bcnt;
        } while(u != v);
    }
}

int cnt[MX];
LL solve(int n) {
    Init_tarjan(n);
    for (int i = 1; i <= n; i++) {
        if (!DFN[i]) Tarjan(i);
    }
    LL ans = 0;
    for(int i = 1; i <= n; i++) {
        cnt[belong[i]]++;
    }
    for(int i = 1; i <= Bcnt; i++) {
        ans += (LL)cnt[i] * (cnt[i] - 1) / 2;
    }
    return ans;
}

int main() {
    int n, m; //FIN;
    scanf("%d%d", &n, &m);
    edge_init();
    for(int i = 1; i <= m; i++) {
        int u, v;
        scanf("%d%d", &u, &v);
        edge_add(u, v);
    }

    LL ans = 0;
    printf("%lld\n", solve(n));
    return 0;
}


你可能感兴趣的:(强连通分量 CCF201509-4 高速公路)