码迷,mamicode.com
首页 > 其他好文 > 详细

【Luogu】P2607骑士(基环树DP)

时间:2018-01-03 17:29:57      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:using   har   lld   char   getchar   gpo   turn   solution   https   

  题目链接

  这题……好吧我比着题解打的

  题解连接

#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<cctype>
#include<algorithm>
#define maxn 1000200
using std::max;
inline long long read(){
    long long num=0,f=1;
    char ch=getchar();
    while(!isdigit(ch)){
        if(ch==-)    f=-1;
        ch=getchar();
    }
    while(isdigit(ch)){
        num=num*10+ch-0;
        ch=getchar();
    }
    return num*f;
}

struct Edge{
    int next,to;
}edge[maxn*2];
int head[maxn],num;
inline void add(int from,int to){
    edge[++num]=(Edge){head[from],to};
    head[from]=num;
}

int fa[maxn];
long long f[maxn][2];
bool vis[maxn];
int q[maxn];
int ban;
long long ans;
void dfs(int x){
    vis[x]=1;
    f[x][0]=0;
    f[x][1]=q[x];
    for(int i=head[x];i;i=edge[i].next){
        int to=edge[i].to;
        if(to==ban){
            f[to][1]=-100000000;
            continue;
        }
        dfs(to);
        f[x][0]+=max(f[to][1],f[to][0]);
        f[x][1]+=f[to][0];
    }
    return;
}
        

int main(){
    int n=read();
    for(int i=1;i<=n;++i){
        q[i]=read();
        fa[i]=read();
        add(fa[i],i);
    }
    for(int i=1;i<=n;++i){ 
        if(!vis[i]){
            int p=i;
            while(!vis[p]){
                vis[p]=1;
                p=fa[p];
            }
            ban=p;
            dfs(p);
            long long now=max(f[p][0],f[p][1]);
            p=fa[p];ban=p;
            dfs(p);
            ans+=max(now,max(f[p][1],f[p][0]));
        }
    }
    printf("%lld",ans);
    return 0;
}

 

【Luogu】P2607骑士(基环树DP)

标签:using   har   lld   char   getchar   gpo   turn   solution   https   

原文地址:https://www.cnblogs.com/cellular-automaton/p/8184388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!