ZOJ3777Problem Arrangement(状态压缩dp)

题目传送门:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3777

题意:给出n道题目以及每一道题目在不同顺序做的时候的兴趣值,让你求出所有的做题顺序与所有做题顺序中兴趣值不小于m的比例。按一个最简分数表示。

分析:

全排列肯定会超时,所以只能用状压。但是想状压的时候,我想到的只是记录已经安排好了几个做题,但不知道怎么确定所有的n的题目中是哪几个被安排好了。所有就被卡主了。其实把安排了几个题当做状态就可以,不需要去管到底安排好的到底是前面的题还是后面的题,然后用所有待选题目中的前几个去满足上面的那几个安排好了的题就行,状态的转移就相当于了一个全排列的过程。


#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
int dp[1<<13][510];
int f[15], a[15][15];
bool vis[1<<13];
void init()
{
    f[1] = 1;
    for(int i = 2; i <= 12; i++)
        f[i] = f[i-1]*i;
}
int main()
{
    int T, n, m;
    init();
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
                scanf("%d", &a[i][j]);
        memset(dp, 0, sizeof(dp));
        memset(vis, false, sizeof(vis));
        dp[0][0] = 1;
        queue<pii> q;
        q.push(pii(0, 0));
        while(!q.empty())
        {
            pii now = q.front();
            q.pop();
            int s = now.first;
            int cnt = now.second;
            for(int i = 1; i <= n; i++)
            {
                if(s>>(i-1) & 1)
                    continue;
                for(int v = 0; v <= m; v++)
                {
                    if(dp[s][v] == 0)
                        continue;
                    if((v + a[cnt+1][i]) >= m)
                        continue;
                    dp[s|(1<<(i-1))][v+a[cnt+1][i]] += dp[s][v];
                    if(!vis[s|(1<<(i-1))] && cnt + 1 != n)
                    {
                        q.push(pii(s|(1<<(i-1)), cnt+1));
                        vis[s|(1<<(i-1))] = true;
                    }
                }
            }
        }
        int ans = 0, all = f[n];
        for(int i = 0; i < m; i++)
            ans += dp[(1<<n)-1][i];
        ans = all - ans;
        int gcd = __gcd(all, ans);
        all /= gcd;ans /= gcd;
        if(ans == 0)
            printf("No solution\n");
        else
            printf("%d/%d\n", all, ans);
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值