您的位置:首页 > 其它

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

2015-11-24 20:54 357 查看
第一次状态压缩DP,刚开始使用贪心策略,后来找到反例。

输入:
5
3
a 1 1
b 2 1
c 1 1
你的输出:
2
a
c
b
正确答案:
2
a
b
c

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

但是如果遇到类似题目只要求最小扣分,那么一定要用贪心,因为这题只有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;
struct node
{
int dead,spend;
char name[105];
}a[15];
struct dode
{
int t,now,pre,score;
}dp[1<<15];
int main()
{
//	freopen("t.txt","r",stdin);
int i,j,t,n,temp,last,score2;
scanf("%d",&t);
while(t--)
{
memset(dp,0,sizeof(dp));
scanf("%d",&n);
for(i = 0; i < n; i++)
{
scanf("%s",a[i].name);
scanf("%d%d",&a[i].dead,&a[i].spend);
}
int end = 1<<n;
for(i = 1; i < end; i++)
{
dp[i].score = 1<<30;
for(j = 0; j < n; j++)
{
temp = 1<<j;
if(i&temp)
{
last = i-temp;
score2 = dp[last].t + a[j].spend - a[j].dead;
if(score2 < 0) score2 = 0;
if(score2 + dp[last].score <= dp[i].score)
{
dp[i].score = score2 + dp[last].score;
dp[i].now = j;
dp[i].pre = last;
dp[i].t = dp[last].t + a[j].spend;
}
}
}
}
stack<int>s;
int q = end - 1;
printf("%d\n",dp[q].score);
while(q)
{
s.push(dp[q].now);
q = dp[q].pre;
}
while(!s.empty())
{
printf("%s\n",a[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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: