UVA 10817 Headmaster's Headache

本文介绍了一种使用状态压缩动态规划解决教师资源分配问题的方法。针对每门课程至少需要两名教师的要求,通过复杂的位操作来表示每门课程教师的状态,并采用0-1背包问题的思路求解最小成本。

        状态压缩dp,但是要求的是每门功课至少有两名老师,所以状态有些复杂,可以用(1  << 2 * s) 的状态表示,前s位表示该位是否有两位老师,后s位表示有一位老师,在合并的时候注意前s位要用或运算。然后0-1背包即可。

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>

#define LL long long
#define CLR(a, b) memset(a, b, sizeof(a))

const int N = 222;
const int INF = 1e9;
int c[N], dp[1 << 18], th[N];
int ret;

using namespace std;

int input()
{
    char ch = ' ';
    ret = 0;
    while(ch > '9' || ch < '0') ch = getchar();
    do
    {
        if(ch == ' ')
        {
            return 1;
        }
        else if(ch == '\n')
        {
            return 0;
        }
        else ret = ret * 10 + ch - '0';
    }while(ch = getchar());
}

int main()
{
    //freopen("input.txt", "r", stdin);
    int s, m, n, i, j, l, r, pay, ans;
    while(cin >> s >> m >> n, s)
    {
        CLR(th, 0);getchar();
        pay = l = r = 0;
        for(i = 0; i < n + m; i ++)
        {
            input();c[i] = ret;
            while(input())
            {
                th[i] += (1 << ret - 1);
            }
            th[i] += (1 << ret - 1);
            if(i < m)
            {
                pay += c[i];
                if(r & th[i]) l |= (r & th[i]);
                r ^= th[i];
            }
        }
        for(i = 0; i < (1 << (2 * s)); i ++) dp[i] = INF;
        dp[(l << s) + r] = pay;
        for(i = m; i < n + m; i ++)
        {
            int tmp = (1 << (2 * s));
            for(j = tmp - 1; j >= (l << s) + r; j --)
            {
                int cnt = (((j & th[i]) | (j >> s)) << s) + ((j & ((1 << s) - 1)) ^ th[i]);//算可以推出的下标。前s位加后s位的形式。
                dp[cnt] = min(dp[cnt], dp[j] + c[i]);
            }
        }
        ans = INF;
        for(i = ((1 << 2 * s) - (1 << s)); i < (1 << 2 * s); i ++) ans = min(ans, dp[i]);
        cout << ans << endl;
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值