Codechef Little Elephant and Painting

Problem Description

Little Elephant from Zoo of Lviv likes to paint.
He has n objects to paint, ordered in a row and numbered form left to right starting from 1. There are totally c colors, numbered from 0 to c-1. At the beggining all objects are colored in color with number 1. When object with color a is painted in color b, the resulting color will have number (a*b) mod c.
Little Elephant is going to make k turns. At i-th (0-based numeration) turn he will randomly choose any subset (even empty) of objects with indices in range [Li; Ri] (inclusive) and paint all objects in chosen subset with random color (the same for all objects in the subset).
Little Elephant wants to know the expected sum of all colors over all n objects after making all k turns. Help him.

Input

First line contain single integer T - the number of test cases. T test cases follow. First line of each test case contains three integers n, c and k. Next k lines of each test case contain k pairs of integers Li and Ri, one pair per line.

Output

In T lines print T real numbers - the answers for the corresponding test cases.
Any results within 10^-6 absolute error will be accepted.

Constraints

1 <= T <= 10
1 <= n, k <= 50
2 <= c <= 100
1 <= Li <= Ri <= n

Example

Input:

2
4 3 4
1 2
2 4
3 3
1 4
7 10 7
7 7
3 4
1 2
5 5
4 5
2 7
3 3


Output:

3.444444444
22.943125000

题解

很好的期望dp。

对于任意一个物品,我们要知道它k次操作后变成0~c每个颜色的概率。

现在考虑每一次操作,f[i][j]表示i次操作后一个点颜色变为j,那么f[i][j]对f[i+1][j]有贡献,即该次操作没有改变该物体的颜色,因为每次操作对于一个物体来说只有两种可能性:改或不改,分别有1/2的概率。以上是不改的。而对于“改”,f[i][(j*k)%c]+=f[i][j]/(2*c),因为选择一个颜色有1/c的概率,而改有1/2的概率。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<cmath>
#include<algorithm>
#define MAXN 55
using namespace std;
int T,n,c,K,cs[MAXN],maxc;
double f[MAXN][MAXN<<1],ans;
void init()
{
	scanf("%d%d%d",&n,&c,&K);
	int i,j,x,y;
	memset(cs,0,sizeof(cs));
	maxc=0;
	for(i=1;i<=K;i++)
	   {scanf("%d%d",&x,&y);
	    for(j=x;j<=y;j++)
		   {cs[j]++; maxc=max(maxc,cs[j]);}
	   }
}
void dp()
{
	int i,j,k;
	memset(f,0,sizeof(f));
	f[0][1]=1;
	for(i=0;i<maxc;i++)
	for(j=0;j<c;j++)
	   {f[i+1][j]+=f[i][j]/2;
	    for(k=0;k<c;k++)
	       f[i+1][(j*k)%c]+=f[i][j]/(2*c);
	   }
	ans=0;
	for(i=1;i<=n;i++)
	for(j=0;j<c;j++)
	   ans+=f[cs[i]][j]*j;
	printf("%.9lf\n",ans);
}
int main()
{
	scanf("%d",&T);
	while(T--)
	   {init(); dp();}
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值