HUD 1074 doing homework(状压DP)

状态压缩的一道题,刚开始我根本想不到是状态压缩,我以为会用什么贪心算法做出来,看了网上大神的解法才知道是要位压缩,感觉不可思议。

状态变量s从0—>(1<<n-1),然后再加上一个循环变量for(i:1->n),二进制的s里面第j位为1表示第j个作业已经做完了,然后对做完第j个作业的之后的状态进行刷新;换一种说法就是刷新s状态是根据能达到这一状态做的最后一种作业来定的;


Doing Homework

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8124    Accepted Submission(s): 3733


Problem Description
Ignatius has just come back school from the 30th ACM/ICPC. Now he has a lot of homework to do. Every teacher gives him a deadline of handing in the homework. If Ignatius
#include<stdio.h>
#include<string.h>
#include<math.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXNUM=1<<15;
const int INF = 0x7fffffff;
struct
{
    char name[101];
    int deadline;
    int workday;
}homework[20];
struct
{
    int reduce;
    int cost;
    int piror;  //该状态之前的最后写的一们作业;
}dp[MAXNUM+100];
int cases,n;
int visited[MAXNUM+100];
bool  loop()
{

    if(!cases)
        return false;
    cases--;
    memset(visited,0,sizeof(visited));
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>homework[i].name>>homework[i].deadline>>homework[i].workday;
    }
    long long maxstation=(1<<n)-1;
    for(long s=0;s<maxstation;s++)
    {
          for(int i=1;i<=n;i++)
          {
              if((s&(1<<(i-1)))==0)
              {
                  long long thistation=s+(1<<(i-1));
                  int thiswork=dp[s].cost+homework[i].workday;
                  int thisreduce=thiswork-homework[i].deadline;
                  if(thisreduce<0)
                    thisreduce=0;
                  if((visited[thistation]&&dp[s].reduce+thisreduce<dp[thistation].reduce))
                  {
                      dp[thistation].reduce=dp[s].reduce+thisreduce;
                      dp[thistation].piror=i;
                      dp[thistation].cost=thiswork;
                  }
                  if((visited[thistation]==0))
                  {
                       dp[thistation].reduce=dp[s].reduce+thisreduce;
                      dp[thistation].piror=i;
                      dp[thistation].cost=thiswork;
                      visited[thistation]=1;
                  }
              }
          }
    }
    long long total=(1<<n)-1;
    cout<<dp[total].reduce<<endl;
    int j=n;
    int outs[n+1];
    while(total)
    {
        int k=dp[total].piror;
        outs[j]=k;
        j--;
        total-=(1<<(k-1));
    }
    for(int i=1;i<=n;i++)
    {
        cout<<homework[outs[i]].name<<endl;
    }
    return true;
}
int main()
{
    cin.tie(0);
    cin.sync_with_stdio(false);
  // freopen("in.txt","r",stdin);
    cin>>cases;
    while(loop());
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值