Zoj 3162 to go or not to go digital DP

Source: Internet
Author: User

Http://acm.zju.edu.cn/onlinejudge/showProblem.do? Problemid = 3179

Example:

Give you two numbers a B, such as 3 5

3-> the binary number of 5 is 11 100 101 110.

Returns the probability of occurrence of each number.

In the preceding example, P = 1/4*(1 + 1/3 + 2/3 + 2/3)

Method: preprocessing a DP [I] [2]: DP [I] [1] indicates the sum of 1 in the binary number with the highest bit as 1 and the length as I

DP [I] [0] indicates the sum of 1 in the binary number where the highest bit is 0 and the length is I.

This question has a special place in Statistics. Binary numbers of the same length must be processed together.

Then you can take a closer look at the boundary.

#include<stdio.h>#include<string.h>double dp[30][2];double d[30][2];void init(){memset(dp,0,sizeof(dp));memset(d,0,sizeof(d));for(int i=1;i<30;i++){    dp[i][1]=dp[i-1][1]+dp[i-1][0]+(1<<(i-1));dp[i][0]=dp[i-1][1]+dp[i-1][0];}}double CC(int num){double sum=0;int cnt=0;for(int i=29;i>=0;i--){if(num&(1<<i)){sum+=dp[i+1][0];sum+=(double)(1<<i)*cnt;cnt++;}}sum+=cnt;return sum;}double calc(int a,int b){double cnt=b-a+1;double sum=0;int f1,f2;for(int i=29;i>=0;i--){if(a&(1<<i)){f1=i;break;}}for(int i=29;i>=0;i--){if(b&(1<<i)){f2=i;break;}}for(int i=f1+2;i<=f2;i++)sum+=dp[i][1]/i;if(f2-f1==0){double num=CC(b)-CC(a-1);sum=num/(f1+1);}else {int p=(1<<(f1+1))-1;double num=CC(p)-CC(a-1);sum+=num/(f1+1);p=(1<<f2);num=CC(b)-CC(p-1);sum+=num/(f2+1);}return sum/cnt;}int main(){int t,a,b;init();scanf("%d",&t);while(t--){scanf("%d%d",&a,&b);printf("%lf\n",calc(a,b));}return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.