洛谷tarjan缩点

P3387

 

思路:

缩点后重建图,然后dfs记忆化搜索

注意重建图还是有向图,我给建成无向图,改了一早晨、、、

#include 
using namespace std;
typedef long long ll;
const int maxn = 1e4+7;
int n,m,tot,cnt = 1,point[maxn],head[maxn],low[maxn],dfn[maxn];
int sum_point[maxn],tos,pre[maxn],Edge[(maxn<<1)+(maxn<<3)][2];
stack S;
bool vis[maxn];
struct node{int to,next;}E[(maxn<<1)+(maxn<<3)];
void add(int u,int v){E[cnt] = node{v,head[u]},head[u] = cnt++;}
void tarjan(int u){
    low[u] = dfn[u] = ++tot;
    vis[u] = true,S.push(u);
    for(int i=head[u],v;i;i=E[i].next){
        v = E[i].to;
        if(!dfn[v])
            tarjan(v),low[u] = min(low[u],low[v]);
        else if(vis[v])
            low[u] = min(low[u],dfn[v]);
    }
    if(low[u] == dfn[u]){
        while(true){
            int now = S.top();
            S.pop();
            vis[now] = false;
            sum_point[tos] += point[now],pre[now] = tos;
            if(u == now)break;
        }
        tos++;
    }
}
int dfs(int u){
    if(point[u] != -1)return point[u];
    int ans = sum_point[u];
    for(int i=head[u],v;i;i = E[i].next){
        v = E[i].to;
        ans = max(ans,sum_point[u]+dfs(v));
    }
    return point[u] = ans;
}
signed main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)scanf("%d",&point[i]);
    for(int i=1;i<=m;i++)scanf("%d%d",&Edge[i][0],&Edge[i][1]),add(Edge[i][0],Edge[i][1]);
    for(int i=1;i<=n;i++)if(!dfn[i])tarjan(i);
    cnt = 1,memset(head,0,sizeof(head));//重建图
    for(int i=1;i<=m;i++)if(pre[Edge[i][0]] != pre[Edge[i][1]])add(pre[Edge[i][0]],pre[Edge[i][1]]);
    memset(point,-1,sizeof(point));
    int ans = -0x3f3f3f3f;
    //printf("%d\n",tos);
    for(int i=0;i

 

你可能感兴趣的:(模板类(什么,这也是模板))