zoukankan      html  css  js  c++  java
  • 对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; }
  • 相关阅读:
    ant design pro梳理
    JSON.stringify()
    数组小细节
    js this细节
    策略模式解决if-else过多
    使用useState的赋值函数异步更新问题
    Hook
    React Api
    Intent
    树的非递归遍历
  • 原文地址:https://www.cnblogs.com/Accepting/p/11276905.html
Copyright © 2011-2022 走看看