zoukankan      html  css  js  c++  java
  • 洛谷1352 CODEVS1380 没有上司的舞会

    洛谷的测试数据貌似有问题,4个点RE不可避

    CODEVS可AC


    ——————

    10分钟后追记:在洛谷把数组范围开到10000+就过了

    ——————


    题目描述 Description

          Ural大学有N个职员,编号为1~N。他们有从属关系,也就是说他们的关系就像一棵以校长为根的树,父结点就是子结点的直接上司。每个职员有一个快乐指数。现在有个周年庆宴会,要求与会职员的快乐指数最大。但是,没有职员愿和直接上司一起与会。

    输入描述 Input Description

    第一行一个整数N。(1<=N<=6000)
    接下来N行,第i+1行表示i号职员的快乐指数Ri。(-128<=Ri<=127)
    接下来N-1行,每行输入一对整数L,K。表示K是L的直接上司。
    最后一行输入0,0。

    输出描述 Output Description

    输出最大的快乐指数。

    样例输入 Sample Input

    7
    1
    1
    1
    1
    1
    1
    1
    1 3
    2 3
    6 4
    7 4
    4 5
    3 5
    0 0

    样例输出 Sample Output

    5

    数据范围及提示 Data Size & Hint

    各个测试点1s

    标准做法是用邻接表,然而我直接模拟建了个树

    vector大法好


    设f[结点][不选==1/选==2]=最大价值。我们可以知道,对于结点x,如果选了x,则f[x][2]=val[x]+f[x的子树][1];如果不选x,则f[x][1]=0+f[x的子树][1或2(因为可以连子树也不选)]


     1 #include<iostream>
     2 #include<cstdio>
     3 #include<algorithm>
     4 #include<cmath>
     5 #include<vector>
     6 using namespace std;
     7 struct tr{
     8     int val;
     9     int fa;
    10     vector<int> ch;
    11 }t[8000];
    12 int n;
    13 int f[8000][2];//[结点][不选/选]=分数 
    14 void dp(int x){
    15     int i,j;
    16     f[x][1]=0;
    17     f[x][2]=t[x].val;
    18     if(t[x].ch.empty())return;//return t[f].val;
    19     for(i=0;i<t[x].ch.size();i++ ){
    20         int it=t[x].ch[i];
    21         dp(it);
    22         f[x][1]=max(f[x][1],max(f[x][1]+f[it][2],f[x][1]+f[it][1]));//不选x 
    23         //f[x][1]=max(f[x][1],f[x][1]+f[it][1]);
    24         f[x][2]=max(f[x][2],f[x][2]+f[it][1]);//选x 
    25 //        printf("root: %d child: %d  f1:%d  f2:%d 
    ",x,it,f[x][1],f[x][2]);
    26     }
    27     return;
    28 }
    29 int main(){
    30     scanf("%d",&n);
    31     int i,j;
    32     for(i=1;i<=n;i++){
    33         scanf("%d",&t[i].val);
    34     }
    35     int l,k;
    36     for(i=1;i<n;i++){
    37         scanf("%d%d",&l,&k);
    38         t[l].fa=k;//建树
    39         t[k].ch.push_back(l);
    40     }
    41     int father=1;
    42     while(t[father].fa!=0)father=t[father].fa;//寻找整棵树的父亲
    43 
    44     dp(father);
    45     printf("%d",max(f[father][1],f[father][2]));
    46     return 0;
    47 }





  • 相关阅读:
    用struct定义函数
    三、OCTAVE画图
    二、OCTAVE 移动数据
    SQL复习
    Flink处理迟到的数据
    LeetCode题目学习
    CentOS7安装pycharm
    IntelliJ IDEA 刷题利器 LeetCode 插件
    Redis命令学习
    项目杂记
  • 原文地址:https://www.cnblogs.com/SilverNebula/p/5550575.html
Copyright © 2011-2022 走看看