Tarjan 缩点模板(洛谷P3387)

来源:互联网 发布:国债收益率升高知乎 编辑:程序博客网 时间:2024/06/06 00:57

题目背景

缩点+DP

题目描述

给定一个n个点m条边有向图,每个点有一个权值,求一条路径,使路径经过的点权值之和最大。你只需要求出这个权值和。

允许多次经过一条边或者一个点,但是,重复经过的点,权值只计算一次。

输入输出格式

输入格式:
第一行,n,m

第二行,n个整数,依次代表点权

第三至m+2行,每行两个整数u,v,表示u->v有一条有向边

输出格式:
共一行,最大的点权之和。

输入输出样例

输入样例#1:
2 2
1 1
1 2
2 1
输出样例#1:
2

说明

n<=10^4,m<=10^5,|点权|<=1000 算法: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;}
原创粉丝点击