hihocoder 1185(tarjan缩点)

复习复习tarjan算法

题目链接:hihocoder 1185

#include
#include
#include
#include 
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define maxn 20005
#define maxm 100005
#define rd(x) scanf("%d", &x)
#define rd2(x, y) scanf("%d%d", &x, &y)
struct Edge{
    int to,next;
}edge[maxm *4];
int head[maxn],tot;
int low[maxn],dfn[maxn],Stack[maxn];
int belong[maxn]; // 1~scc
int Index,top;
int scc; //强连通分量的个数
bool instack[maxn];
long long int num[maxn];
int w[maxn];
void addedge(int u, int v){
    edge[tot].to = v;edge[tot].next = head[u];head[u] = tot++;
}
void tarjan(int u){
    int v;
    low[u] = dfn[u] = ++Index;
    Stack[top++] = u;
    instack[u] = true;
    for(int i = head[u]; i != -1; i = edge[i].next){
        v = edge[i].to;
        if(!dfn[v]){
            tarjan(v);
            if(low[u] > low[v]) low[u] = low[v];
        }
        else if(instack[v] && low[u] > dfn[v]) low[u] = dfn[v];
    }
    if(low[u] == dfn[u]){
        scc++;
        do{
            v = Stack[--top];
            instack[v] = false;
            belong[v] = scc;
            num[scc] += w[v];
        }
        while(v != u);
    }
}
void solve(int N){
    memset(dfn, 0, sizeof(dfn));
    memset(instack, false, sizeof(instack));
    memset(num, 0, sizeof(num));
    Index = scc = top = 0;
    /*for(int i = 1; i <= N; i++){
        if(!dfn[i]) tarjan(i);
    }*/
    tarjan(1);
}
void init(){
    tot = 0;
    memset(head, -1, sizeof(head));
}
int head2[maxn];
long long int dfs(int u){
    long long int mx = 0;
    for(int i = head2[u]; i != -1; i = edge[i].next){
        long long int tmp = dfs(edge[i].to);
        if(mx < tmp) mx = tmp;
    }
    return mx + num[u];
}
int main()
{
    int n, m, a, b;
    init();
    rd2(n, m);
    for(int i = 1; i <= n; i++) rd(w[i]);
    for(int i =1; i <= m; i++){
        rd2(a, b);
        addedge(a, b);
    }
    memset(belong, 0, sizeof(belong));
    solve(n);

    //  重新建图
    memset(head2, -1, sizeof(head2));
    for(int i = 1; i <= n; i++){
        for(int j = head[i]; j != -1; j = edge[j].next){
            int v = edge[j].to;
            if(!belong[i]) continue;
            if(belong[v] != belong[i]){
                edge[tot].to = belong[v];
                edge[tot].next = head2[belong[i]];
                head2[belong[i]] = tot++;
            }
        }
    }
    printf("%lld\n",dfs(belong[1]));

    return 0;
}


你可能感兴趣的:(图)