zoukankan      html  css  js  c++  java
  • 状压dp (记录路径) 做家庭作业 HDU

    题意:有n门课,每门课有截止时间和完成所需的时间,如果超过规定时间完成,每超过一天就会扣1分,问怎样安排做作业的顺序才能使得所扣的分最小。

    分析:只有15门课,可以通过状压,暴力枚举每一种情况,并且在DP的时候要记录路径,方便之后的输出。

    一维状压dp的写法:先枚举所有状态,再枚举每门课,如果这门课可以构成这个状态,就用状态转移,记录最小值,(因为还有字典序要求,所以 j要从n-1到0枚举,确保n-1距离最终状态11111尽可能远)。

    记录路径的方法:记录到达状态的前驱

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    
    const int INF=0x3f3f3f3f;
    const int maxn=10009;
    struct node{
        char str[30];
        int x,y;
    }a[17];
    int dp[1<<16],pre[1<<16],cnt,time[1<<16];
    int n;
    
    void print(int x){
        if(x==0) return;
        print(x-(1<<pre[x]));
        printf("%s
    ",a[pre[x]].str);
    }
    
    int main(){
        int T;
        scanf("%d",&T);
        while(T--){
            scanf("%d",&n);
            memset(dp,0,sizeof(dp));
            memset(pre,0,sizeof(pre));
            memset(time,0,sizeof(time));
            for(int i=0;i<n;i++){
                cin>>a[i].str>>a[i].x>>a[i].y;
            }
            int tot=(1<<n);                      //一维的状压dp
    //        printf("%d
    ",dfs(0,0,0));
            for(int i=1;i<tot;i++){          
                dp[i]=INF;                   //i从1到tot ,实现枚举所有状态 ,这里的状态是目标状态 
                for(int j=n-1;j>=0;j--){    //j从 n-1到 0,就可以实现把n-1放在后面完成 (最后是11111,前面就优先判断完成n-1)
                    int temp=1<<j;
                    if(!(i&temp)) continue;      //状态i不存在状态j,那么就不能通过完成作业j到达状态i 
                    int s=time[i-temp]+a[j].y-a[j].x;
                    s=s<0?0:s;
                       if(dp[i]>dp[i-temp]+s){
                        dp[i]=dp[i-temp]+s;
    //                    printf("dp=%d
    ",dp[i]); 
                        time[i]=time[i-temp]+a[j].y;
                        pre[i]=j;      //达到状态i的前驱 
                    }
                }
            }
            printf("%d
    ",dp[tot-1]);
            print(tot-1);
        }
    }
  • 相关阅读:
    HDU 1716 排列2
    HDU 3405 World Islands
    HDU 5624 KK's Reconstruction
    HDU 2689 Tree
    UVA 12075 Counting Triangles
    UVA 11100 The Trip, 2007
    [USACO 2004DEC] Navigation Nightmare
    [USACO 2017DEC] Barn Painting
    [Usaco2017 Dec] A Pie for a Pie
    [USACO 2017DEC] Greedy Gift Takers
  • 原文地址:https://www.cnblogs.com/-Zzz-/p/11416868.html
Copyright © 2011-2022 走看看