• 「LuoguP2014」 选课


    Description

    在大学里每个学生,为了达到一定的学分,必须从很多课程里选择一些课程来学习,在课程里有些课程必须在某些课程之前学习,如高等数学总是在其它课程之前学习。现在有N门功课,每门课有个学分,每门课有一门或没有直接先修课(若课程a是课程b的先修课即只有学完了课程a,才能学习课程b)。一个学生要从这些课程里选择M门课程学习,问他能获得的最大学分是多少?

    Input&&Output

    input

    第一行有两个整数N,M用空格隔开。(1<=N<=300,1<=M<=300)

    接下来的N行,第I+1行包含两个整数ki和si, ki表示第I门课的直接先修课,si表示第I门课的学分。若ki=0表示没有直接先修课(1<=ki<=N, 1<=si<=20)。

    output

    只有一行,选M门课程的最大得分。

    Sample

    Sample Input
    7  4
    2  2
    0  1
    0  4
    2  1
    7  1
    7  6
    2  2
    
    Sample Output
    13

    题解

    为什么都用dfs 拓扑序多好用2333

    首先我们把k==0的课程 的先修课 当作课程0
    
    然后对每个点往它的先修课连一条边 会形成一棵以0为根的树形结构
    
    对每个点记录它连出边的终点编号(to[ x ])和它的入度(rd[ x ])
    然后就可以按拓扑序dp了
    
    记f[i][j]为 在i号点 选了i的子树上(一定包括i 共j个点 最多能拿到的学分
    
    然后跑01背包 转移方程:f[to[x]][i]=max(f[to[x]][i],f[to[x]][i-j]+f[x][j]);
    
    最后结果在f[0][m+1]上

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<queue>
     4 #include<cmath>
     5 using namespace std;
     6 #define R register
     7 int f[307][307];
     8 int to[307];
     9 int rd[307];
    10 queue<int>q;
    11 int main()
    12 {
    13     int n,m;
    14     scanf("%d%d",&n,&m);
    15     for(R int i=1;i<=n;++i)
    16     {
    17         scanf("%d%d",&to[i],&f[i][1]);
    18         rd[to[i]]++;//终点入度++
    19     }
    20     for(R int i=1;i<=n;++i)
    21     if(!rd[i])q.push(i);
    22     while(!q.empty())
    23     {
    24         int x=q.front();q.pop();
    25         for(R int i=m+1;i>=1;--i)
    26         for(R int j=i-1;j>=1;--j)
    27         f[to[x]][i]=max(f[to[x]][i],f[to[x]][i-j]+f[x][j]);//01背包
    28         //
    29         rd[to[x]]--;
    30         if(!rd[to[x]])q.push(to[x]);
    31     }
    32     cout<<f[0][m+1];
    33     return 0;
    34 }
    View Code
  • 相关阅读:
    【zookpeer】Failed to check the status of the service com.xxx.UserSerivce. No provider available for
    【solr】Spring data solr Document is missing mandatory uniqueKey field: id 解决
    【ssm】springmvc-spring-mybatis框架的搭建
    【jdbc】jdbc连接池理解
    【java基础】接口的理解
    【java基础】private protect的理解
    Single Number II
    Single Number I
    Candy
    Gas Station
  • 原文地址:https://www.cnblogs.com/qwerta/p/9389955.html
Copyright © 2020-2023  润新知