【CCF】商路

【60分】

  1 #include<iostream>
  2 #include<cstdio>
  3 #include<cstring>
  4 #include<string>
  5 #include<cmath>
  6 #include<algorithm>
  7 #include<queue>
  8 #include<map>
  9 using namespace std;
 10 typedef long long ll;
 11 const int maxn=1e5+2;
 12 const int maxm=maxn;
 13 const ll mod=1e18;
 14 int fa[maxn];
 15 ll dep[maxn];
 16 ll dp[maxn];
 17 struct node{
 18     ll v;
 19     ll f;
 20 }g[maxn]; 
 21 struct edge{
 22     int to;
 23     int nxt;
 24     ll w;
 25 }e[2*maxm];
 26 int tot;
 27 int n;
 28 
 29 int head[maxn];
 30 void init(){
 31     memset(head,-1,sizeof(head));
 32     tot=0;
 33     memset(dp,-1,sizeof(dp));
 34     memset(dep,0,sizeof(dep));
 35 }
 36 void add(int u,int v,ll w){
 37     e[tot].to=v;
 38     e[tot].w=w;
 39     e[tot].nxt=head[u];
 40     head[u]=tot++;
 41 }
 42 ll dis(int u,int v){
 43     ll tmp=g[u].f-(dep[v]-dep[u]);
 44     tmp=tmp*tmp;
 45     tmp=g[u].v-tmp;
 46     return tmp;
 47 }
 48 void update(int son,int u){
 49     if(u==0) return;
 50     dp[u]=max(dp[u],dp[son]+dis(u,son));
 51     update(son,fa[u]);
 52 }
 53 void dfs(int u){
 54     for(int i=head[u];i!=-1;i=e[i].nxt){
 55         int v=e[i].to;
 56         if(v<u) continue;
 57         dfs(v);
 58     }
 59     if(dp[u]==-1) dp[u]=0;
 60     update(u,fa[u]);
 61 }
 62 void getdepth(int u){
 63     for(int i=head[u];i!=-1;i=e[i].nxt){
 64         int v=e[i].to;
 65         ll w=e[i].w;
 66         if(v<u) continue;
 67         dep[v]=dep[u]+w;
 68         getdepth(v);
 69     }
 70 }
 71 ll work(){
 72     getdepth(1);
 73     dfs(1);
 74     ll ans=0;
 75     for(int i=1;i<=n;i++){
 76         ans=(ans+dp[i])%mod;
 77     }
 78     return ans;
 79 }
 80 int main(){
 81     int T;
 82     scanf("%d",&T);
 83     while(T--){
 84         init();
 85         scanf("%d",&n);
 86         int u;
 87         ll d,v,f;
 88         for(int i=1;i<=n;i++){
 89             scanf("%d%lld%lld%lld",&u,&d,&v,&f);
 90             g[i].v=v;
 91             g[i].f=f;
 92             add(u,i,d);
 93             add(i,u,d);
 94             fa[i]=u;
 95         }    
 96         ll ans=work();
 97         printf("%lld\n",ans);
 98     }
 99     return 0;
100 }
View Code

 

posted @ 2018-06-19 12:38  shulin15  阅读(294)  评论(0编辑  收藏  举报