Tarjan缩点模板(洛谷P3387)

来源:互联网 发布:淘宝网中老年女外套 编辑:程序博客网 时间:2024/06/05 19:19

题解

Tarjan+DAGDP

代码如下

#include<bits/stdc++.h>using namespace std;#define maxn 1000005int n,num_e,dfs_T,ans,m,u,vv,S=0,x,y,scc_num;int b[maxn];struct edge{    int to,nex,fa;}e[maxn];int low[maxn],head[maxn],bj[maxn],val[maxn];int v[maxn],dp[maxn];int sceno[maxn],pre[maxn];stack<int> st;void add_edge(int x,int y){    e[++num_e].to=y;    e[num_e].fa=x;    e[num_e].nex=head[x];    head[x]=num_e;}void scc(int x){    low[x]=pre[x]=++dfs_T;    st.push(x);    for(int o=head[x];o;o=e[o].nex){        if(!pre[e[o].to]) scc(e[o].to),low[x]=min(low[x],low[e[o].to]);        else if(!sceno[e[o].to]) low[x]=min(low[x],pre[e[o].to]);    }    if(low[x]==pre[x]){        scc_num++;        int y;        do{            y=st.top();            st.pop();            sceno[y]=scc_num;            v[scc_num]+=val[y];        }while(x^y);    }}void dfs(int x){    b[x]=1;    for(int i=head[x];i;i=e[i].nex){        int y=e[i].to;        if(!b[y] && x!=y) dfs(y),dp[x]=max(dp[x],dp[y]+v[y]);    }    b[x]=0;}int main(){    scanf("%d%d",&n,&m);    for(int i=1;i<=n;i++) scanf("%d",&val[i]);    for(int i=1;i<=m;i++){        scanf("%d%d",&x,&y);        add_edge(x,y);    }    for(int i=1;i<=n;i++){        if(!pre[i]) scc(i),add_edge(S,i);    }    memset(head,0,sizeof(head));    for(int i=1;i<=num_e;i++){        e[i].fa=sceno[e[i].fa];        e[i].to=sceno[e[i].to];        e[i].nex=head[e[i].fa];        head[e[i].fa]=i;    }    dfs(S);    printf("%d",dp[S]);    return 0;}
原创粉丝点击