• 对01背包路径的记录


    You have a long drive by car ahead. You have a tape recorder, but unfortunately your best music is on CDs.

    You need to have it on tapes so the problem to solve is: you have a tape N minutes long. How to choose tracks from CD to get most out of tape space and have as short unused space as possible.

    Assumptions:

    • number of tracks on the CD does not exceed 20

    • no track is longer than N minutes

    • tracks do not repeat

    • length of each track is expressed as an integer number

    • N is also integer Program should find the set of tracks which fills the tape best and print it in the same sequence as the tracks are stored on the CD

    Input 

       Any number of lines. Each one contains value N, (after space) number of tracks and durations of the tracks.

      For example from first line in sample data: N = 5, number of tracks=3, first track lasts for 1 minute, second one 3 minutes, next one 4 minutes

    output

      Set of tracks (and durations) which are the correct solutions and string ‘sum:’ and sum of duration times.

    Sample Input

      5 3 1 3 4

      10 4 9 8 4 2

       20 4 10 5 7 4

      90 8 10 23 1 2 3 4 5 7

       45 8 4 10 44 43 12 9 8 2

    Same OUpt

      1 4 sum:5

      8 2 sum:10

      10 5 4 sum:19

      10 23 1 2 3 4 5 7 sum:55

       4 10 12 9 8 2 sum:45

    题目大意:就是一张容量为N的CD 问最多能存放多少时长的歌曲:要打印出来存放路径

    AC代码:

    #include<iostream>
    #include<cstring>
    #include<algorithm>
    #include<cstdio>
    using namespace std;
    const int N=1e4+10;
    int v[N];
    int vv[N];
    int dp[N];
    bool pre[N][N];
    int main(){
        int m;
        while(~scanf("%d",&m)){
            int n;
            scanf("%d",&n);
            for(int i=1;i<=n;i++){
                scanf("%d",&v[i]);
            }
            memset(dp,0,sizeof(dp));
            memset(pre,0,sizeof(pre));
            for(int i=1;i<=n;i++){
                for(int j=m;j>=v[i];j--){
                if(dp[j]<=dp[j-v[i]]+v[i]){
                    dp[j]=dp[j-v[i]]+v[i];
                    pre[i][j]=1;//如果第i个歌曲被放进背包,,标记当前背包的位置;
                }
            }
        }
        //对路径的记录
    int i=n,j=m,pos=0; while(i>=1&&j>=0){ if(pre[i][j]) { vv[pos++]=v[i]; j=j-v[i];//第i张歌曲放在了第当背包容量为j-v[i]时,下一步找第i-1张歌曲.(由此的来dp[j]=dp[j-v[i]]+v[i];) } i--; } for(int i=pos-1;i>=0;i--){ printf("%d ",vv[i]); } printf("sum:%d ",dp[m]); } return 0; }
  • 相关阅读:
    一文带你看清HTTP所有概念
    程序员不得不了解的硬核知识大全
    看完这篇HTTP,跟面试官扯皮就没问题了
    ReentrantLock 源码分析从入门到入土
    计算机网络的核心概念
    Kafka 的这些原理你知道吗
    2019 我是怎么熬过来的?
    不懂什么是锁?看看这篇你就明白了
    机器学习——方差、协方差与皮尔逊值
    最小生成树的本质是什么?Prim算法道破天机
  • 原文地址:https://www.cnblogs.com/Accepting/p/11276905.html
Copyright © 2020-2023  润新知