hdu 1074 状态压缩DP 贪心错的原因(D)

来源:互联网 发布:太原新医医院网络平台 编辑:程序博客网 时间:2024/05/29 14:53

题目链接:hdu1074

贪心能够算出正确的分数,但是不一定能得到正确的字典序。 因为贪心的时候根本没有考虑字典序。

但是如果遇到类似题目只要求最小扣分,那么一定要用贪心,因为这题只有15门课,如果课多枚举状态dp的话肯定不行,而贪心就快得多。因此贪心最好也要知道。

即每次都让deadline早的先完成。


因为最多只有15门课程,可以使用二进制来表示所有完成的状况

例如5,二进制位101,代表第一门和第三门完成了,第二门没有完成,那么我们可以枚举1~(1<<n)便可以得出所有的状态

然后对于每一门而言,其状态是t = 1<<i,我们看这门在现在的状态s下是不是完成,可以通过判断s&t是否为1来得到

这门课是否完成。我们可以枚举j 从 0~n-1 来枚举s状态的上一状态。即 s- 1<<j 。比如11111-1=11110,11111-1<<1=11101

我们便可以进行DP了,在DP的时候要记录当前完成的课在now中,记录上一个状态在pre中。然后使用堆栈输出,当然如果不知道堆栈也是可以的。只是堆栈写起来相对简单,但相差其实不多。

注意输入是按字典序输入的。

正确代码

#include<stdio.h>#include<string.h>#include<algorithm>#include<vector>#include<queue>#include<math.h>#include<stack>using namespace std;#define inf 0x3f3f3f3fstruct hw{    char name[105];    int dead,spend;}p[20];struct node{int now,pre,time,score;}dp[1<<15];int n;int main(){    int t;    scanf("%d",&t);    while(t--)    {scanf("%d",&n);for(int i=0;i<n;i++)scanf("%s%d%d",p[i].name,&p[i].dead,&p[i].spend);memset(dp,0,sizeof dp);int ends=1<<n;for(int i=1;i<ends;i++){dp[i].score=inf;for(int j=0;j<n;j++){int tmp=1<<j;if(i&tmp)//判断j这门课程有没有上过   如果上过的话 有之前的状态更新{int last=i-tmp;int score2=dp[last].time+p[j].spend-p[j].dead;if(score2<0)score2=0;if(dp[i].score>=dp[last].score+score2){dp[i].score=dp[last].score+score2;dp[i].time=dp[last].time+p[j].spend;dp[i].pre=last;dp[i].now=j;}}}}stack<int> s;int q=ends-1;printf("%d\n",dp[q].score);while(q){s.push(dp[q].now);q=dp[q].pre;}while(!s.empty()){printf("%s\n",p[s.top()].name);s.pop();}    }}

贪心代码(错的)

#include<stdio.h>#include<string.h>#include<algorithm>#include<vector>#include<queue>#include<math.h>using namespace std;struct hw{    char name[105];    int dead,spend;}p[20];bool cmp(hw a,hw b){    if(a.dead == b.dead)     {        if(strcmp(a.name,b.name) < 0) return 1;        else return 0;    }    else        return a.dead < b.dead;}int main(){//    freopen("t.txt","r",stdin);    int i,t,n,time,ans;    scanf("%d",&t);    while(t--)    {        ans = time = 0;        scanf("%d",&n);        for(i = 0; i < n; i++)        {            scanf("%s",p[i].name);            scanf("%d%d",&p[i].dead,&p[i].spend);        }        sort(p,p+n,cmp);        for(i = 0; i < n; i++)        {            time+=p[i].spend;            if(time > p[i].dead) ans+= time - p[i].dead;        }        printf("%d\n",ans);        for(i = 0; i < n; i++) puts(p[i].name);    }    }