|
F(x)Time Limit: 1000/500 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3768 Accepted Submission(s): 1397
Problem Description
For a decimal number x with n digits (A
nA
n-1A
n-2 ... A
2A
1), we define its weight as F(x) = A
n * 2
n-1 + A
n-1 * 2
n-2 + ... + A
2 * 2 + A
1 * 1. Now you are given two numbers A and B, please calculate how many numbers are there between 0 and B, inclusive, whose weight is no more than F(A).
Input
The first line has a number T (T <= 10000) , indicating the number of test cases.
For each test case, there are two numbers A and B (0 <= A,B < 10 9)
Output
For every case,you should output "Case #t: " at first, without quotes. The
t is the case number starting from 1. Then output the answer.
Sample Input
Sample Output
Source
Recommend
|
先学习一个位运算
<<是左移,比如1<<n,表示1往左移n位,即数值大小2的n次方
>>右移,类似左移,数值大小除以2的n次方
题目意思:对于一个数a,一个数b;
求在[0,b]的范围内有多少个数的F函数的值要小于等于FA;
输出数的个数!
解题思路:
对于每一对a,b所求出的FA 显然都是不一样的!
有错误的做法是:用数位DP把每一个数的 F函数值求出来并和FA 比较,好像这样的思路也是可以的,但是你会发现没有办法保存DP[pos][sum],因为这个DP里面保存的res是针对一个FA所得到的结论,在第二组样例中这样的DP显然就不能重复利用了!如果对每一组样例的DP初始化重新计算,这样你的答案会正确。只是显然这样会TLE。
有正确的做法是:每一次数位DP,其sum值保存的为FA-FX,这样就可以重复利用你的DP啦!
错误代码:
#include<cstdio> #include<cmath> #include<cstring> #include<iostream> using namespace std; #define ll long long int fa; int DP[20][6000]; int str[20]; int multi(int x){ int count=1; int ans=0; while(x){ ans+=(x%10)*count; count<<=1; x=x/10; } return ans; } int dfs(int pos,int sum,int limit){ if(pos<0){ return sum-fa<=0; } if(sum>fa) return 0; if(!limit&&DP[pos][sum]!=-1) return DP[pos][sum]; int res=0; int end=limit?str[pos]:9; for(int i=0;i<=end;i++){ res+=dfs(pos-1,sum+i*(1<<pos),limit&&(i==end)); } return res; } int solve(int x){ int len=0; while(x){ str[len++]=x%10; x=x/10; } len--; return dfs(len,0,1); } int main(){ int cas; int a,b; scanf("%d",&cas); memset(DP,-1,sizeof(DP)); for(int ii=1;ii<=cas;ii++){ scanf("%d%d",&a,&b); fa=multi(a); printf("Case #%d: %d\n",ii,solve(b)); } return 0; }<span style="color:#ff0000;"> </span>
正确代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iostream>
using namespace std;
#define ll long long
int fa;
int DP[20][6000];
int str[20];
int multi(int x){
int count=1;
int ans=0;
while(x){
ans+=(x%10)*count;
count<<=1;
x=x/10;
}
return ans;
}
int dfs(int pos,int sum,int limit){
if(pos<0){
return sum>=0;
}
if(sum<0)
return 0;
if(!limit&&DP[pos][sum]!=-1)
return DP[pos][sum];
int res=0;
int end=limit?str[pos]:9;
for(int i=0;i<=end;i++){
res+=dfs(pos-1,sum-i*(1<<pos),limit&&(i==end));
}
if(!limit)
DP[pos][sum]=res;
return res;
}
int solve(int x){
int len=0;
while(x){
str[len++]=x%10;
x=x/10;
}
len--;
return dfs(len,fa,1);
}
int main(){
int cas;
int a,b;
scanf("%d",&cas);
memset(DP,-1,sizeof(DP));
for(int ii=1;ii<=cas;ii++){
scanf("%d%d",&a,&b);
fa=multi(a);
//cout<<fa<<endl;
printf("Case #%d: %d\n",ii,solve(b));
}
return 0;
}