强连通分量问题

连通性·三

题目传送:hihoCoder - 1185 - 连通性·三

AC代码:

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <utility>
#include <iostream>
#include <algorithm>
#include <functional>
#define LL long long
#define INF 0x7fffffff
using namespace std;

const int maxn = 20005;
int n, m;

int dfn[maxn];
int low[maxn];
int in_stack[maxn];
int col[maxn];
int vis[maxn];

int w[maxn];
int W[maxn];
int indeg[maxn];

pair<int, int> e[100005];
vector<int> G[maxn];
vector<int> G2[maxn];

stack<int> s;

int cur_time, color;
void tarjan(int u) {
    dfn[u] = low[u] = ++ cur_time;
    s.push(u);
    in_stack[u] = 1;
    vis[u] = 1;

    int d = G[u].size();
    for(int i = 0; i < d; i ++) {
        int v = G[u][i];
        if(!vis[v]) {
            tarjan(v);
            low[u] = min(low[u], low[v]);
        }
        else if(in_stack[v]) {
            low[u] = min(low[u], dfn[v]);
        }
    }

    color ++;
    if(dfn[u] == low[u]) {
        int v;
        do {
            v = s.top();
            s.pop();
            in_stack[v] = 0;
            col[v] = color;
            W[color] += w[v];
        } while(v != u);
    }
}

void make_new_graph() {
    for(int i = 0; i < m; i ++) {
        int u = col[e[i].first];
        int v = col[e[i].second];
        if(u == 0 || v == 0) continue;
        //cout << u << " " << v << endl;
        if(u != v) {
            G2[u].push_back(v);
            indeg[v] ++;
        }
    }
}

int ans;
int MAX[maxn];
void toposort() {
    queue<int> que;
    for(int i = 1; i <= color; i ++) {
        if(indeg[i] == 0) {
            que.push(i);
            MAX[i] = W[i];
            //cout << i << " " << W[i] << endl;
            ans = max(MAX[i], ans);
        }
    }

    while(!que.empty()) {
        int u = que.front();
        que.pop();
        int d = G2[u].size();
        for(int i = 0; i < d; i ++) {
            int v = G2[u][i];
            indeg[v] --;
            MAX[v] = max(MAX[v], MAX[u] + W[v]);
            if(indeg[v] == 0) {
                que.push(v);
                ans = max(MAX[v], ans);
                //cout << v << " " << MAX[v] << endl;
            }
        }
    }
}

int main() {
    scanf("%d %d", &n, &m);
    for(int i = 1; i <= n; i ++) {
        scanf("%d", &w[i]);
    }
    for(int i = 0; i < m; i ++) {
        scanf("%d %d", &e[i].first, &e[i].second);
        G[e[i].first].push_back(e[i].second);
    }

    while(!s.empty()) s.pop();
    memset(col, 0, sizeof(col));
    memset(in_stack, 0, sizeof(in_stack));
    cur_time = color = 0;
    tarjan(1);

    make_new_graph();

    ans = 0;
    toposort();
    printf("%d\n", ans);
    return 0;
}

你可能感兴趣的:(ACM,ICPC,强连通分量,hihoCoder)