CodeForces 398B Painting The Wall 概率DP

本文介绍了一个关于n*n网格的随机涂色问题,通过概率论和动态规划的方法,计算出使得每行每列都有被涂过的位置所需的平均次数。文章提供了完整的代码实现,并解释了转移方程。

题目大意:

就是现在有一个n*n的墙, 初始的时候有m个位置被涂过,现在每次从中随机选一个位置,如果没有涂过就涂上,如果涂过就什么也不做, 问需要经过多少次选择使得每行每列都有被涂过的格子


大致思路:

简直和2014年牡丹江现场赛的D题惊人相似...

转移方程细节见代码


代码如下:

Result  :  Accepted     Memory  :  31356 KB     Time  :  124 ms

/*
 * Author: Gatevin
 * Created Time:  2014/12/24 16:01:15
 * File Name: Sora_Kasugano.cpp
 */
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;

//这题和2014年亚洲区预赛牡丹江现场赛的D题真像..

/*
 * 用E[i][j]表示当前有i行j列被占用时到达目标状态的概率,显然E[n][n] = 0
 * E[i][j] = i*j/(n*n)*(E[i][j] + 1) + (n - i)*j/(n*n)*(E[i + 1][j] + 1)
 *         + i*(n - j)/(n*n)*(E[i][j + 1] + 1) + (n - i)*(n - j)/(n*n)*(E[i + 1][j + 1] + 1)
 * 移项求解E[i][j]即可
 * 答案就是E[cntx][cnty], cntx, cnty为起始时被占用的行和列
 */

bool vis[2][2001];
double E[2001][2001];

int main()
{
    int n, m;
    scanf("%d %d", &n, &m);
    int x, y;
    memset(vis, 0, sizeof(vis));
    int cntx = 0, cnty = 0;
    for(int i = 1; i <= m; i++)
    {
        scanf("%d %d", &x, &y);
        if(!vis[0][x]) cntx++;
        if(!vis[1][y]) cnty++;
        vis[0][x] = vis[1][y] = 1;
    }
    E[n][n] = 0;
    for(int i = n; i >= cntx; i--)
        for(int j = n; j >= cnty; j--)
        {
            if(i == n && j == n) continue;
            E[i][j] = 0;
            if(i + 1 <= n && j + 1 <= n)
                E[i][j] += (n - i)*(n - j)*1./(n*n)*(E[i + 1][j + 1] + 1);
            if(i + 1 <= n)
                E[i][j] += (n - i)*j*1./(n*n)*(E[i + 1][j] + 1);
            if(j + 1 <= n)
                E[i][j] += i*(n - j)*1./(n*n)*(E[i][j + 1] + 1);
            E[i][j] += i*j*1./(n*n);
            E[i][j] /= (1. - i*j*1./(n*n));
        }
    printf("%.4f\n", E[cntx][cnty]);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值