【题解】没有上司的舞会

时间:2019-06-12
本文章向大家介绍【题解】没有上司的舞会,主要包括【题解】没有上司的舞会使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

【题解】没有上司的舞会

5401 没有上司的舞会

我是萌新刚学OI,请问这道树上DP怎么做?

太难了不会啊看了题解才会的。

\(dp(i,1/0)\)表示....算了太难了讲不清楚...

不会怎么DFS,只会常数内存都更小的BFS,球大神教我

//@winlere
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>

using namespace std;  typedef long long ll;
inline int qr(){
      register int ret=0,f=0;
      register char c=getchar();
      while(c<48||c>57)f|=c==45,c=getchar();
      while(c>=48&&c<=57) ret=ret*10+c-48,c=getchar();
      return f?-ret:ret;
}

const int maxn=6e3+5;
int r[maxn];
int dr[maxn];
int in[maxn];
int w[maxn];
int dp[maxn][2];
int n,boss;
queue< int > q;

inline void bfs(){
      while(q.size())q.pop();
      for(register int t=1;t<=n;++t)
        if(dr[t]==1&&t!=boss)
          q.push(t);
      while(!q.empty()){
        register int temp=q.front();
        q.pop();
        dp[r[temp]][0]+=max(dp[temp][1]+w[temp],dp[temp][0]);
        dp[r[temp]][1]+=dp[temp][0];
        if(!in[r[temp]]&&r[temp]) in[r[temp]]=1,q.push(r[temp]);
      }
}

int main(){
#ifndef ONLINE_JUDGE
      freopen("in.in","r",stdin);
      //freopen("out.out","w",stdout);
#endif
      n=qr();
      for(register int t=1;t<=n;++t)
        w[t]=qr();
      if(n==1) return cout<<max(w[1],0)<<endl,0;
      for(register int t=1;t< n;++t){
        register int t1=qr(),t2=qr();
        r[t1]=t2;
        ++dr[t1];++dr[t2];
      }
      for(register int t=1;t<=n;++t)
        if(!r[t]) boss=t;
      bfs();
      cout<<dp[0][0]<<endl;
      return 0;
}

原文地址:https://www.cnblogs.com/winlere/p/11010288.html