问题
Let A=∑ni=1ai∗10n−i(1≤ai≤9)A=∑i=1nai∗10n−i(1≤ai≤9)(nn is the number of AA’s digits). We call AA as “beautiful number” if and only if a[i]≥a[i+1]a[i]≥a[i+1] when 1≤i
题解
暴力打表 O(n)
我们跑[1,1e9] 的所有满足这个条件的数。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
int a[1299] ={自己打表};
int L,R;
int ans;
int main()
{
//freopen("c:/in.txt","r",stdin);
ios::sync_with_stdio(0);cin.tie(0);
int T;
cin>>T;
while(T--){
ans = 0;
cin>>L>>R;
for(int i = 0;i<1299;i++)
if(a[i]>=L&&a[i]<=R) ans++;
cout<<ans<<endl;
}
}
暴力打表源代码
/*暴力求解,写入文件*/
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
int find(int x){
int y = x;
int a[12];
int j = 0;
while(x){
a[j++] = x%10;
x/=10;
}
for(int i=0;i<j-1;i++){
if(a[i]==0||a[i+1]<a[i]||a[i+1]%a[i]!=0)return 0;
}
return y;
}
int main(){
fstream fFile;
int s = 0;
fFile.open("f:\\1.txt", ios::out);
for(int i =1;i<=1000000000;i++){
int yy = find(i);
if(yy){
fFile <<yy<<',';
s++;
}
} printf("%d\n",s);
}
dfs
最大也就10个位,暴力dfs每一个位。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long LL;
int ans;
int L,R;
void dfs(LL num,int pre)
{
if(num>R) return ;
if(num>=L) ans++;
for(int i=1;i<=pre;i++){
if(pre%i==0) dfs(num*10+i,i);
}
}
int main()
{
#ifdef DEBUG
freopen("C:\\in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
#endif
ios::sync_with_stdio(0);cin.tie(0);
int T;
cin>>T;
while(T--){
ans=0;
cin>>L>>R;
for(int i=1;i<=9;i++){
dfs(i,i);
}
cout<<ans<<endl;
}
}
数位dp
在dfs上加记忆化搜索
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long LL;
#define ms(a, b) memset(a, b, sizeof(a))
int L,R;
int ans;
int a[15];
int dp[25][10];
int dfs(int pos,bool lead,bool limit,int pre)
{
if(pos == 0) return 1;
if(!limit && !lead && dp[pos][pre]!=-1) return dp[pos][pre];
int up=limit?a[pos]:9;
LL ans=0;
for(int i=0;i<=up;i++){
if(lead||pre>=i&&i!=0&&pre%i==0){
ans+=dfs(pos-1,lead&&i==0,limit&&i==a[pos],i);
}
}
if(!limit&&!lead) dp[pos][pre] = ans;
return ans;
}
int solve(int x)
{
int len = 0;
while(x){
a[++len] = x%10;
x/=10;
}
return dfs(len, true, true, 0);
}
int main()
{
//freopen("c:/in.txt","r",stdin);
ios::sync_with_stdio(0);cin.tie(0);
int t;
cin>>t;
ms(dp,-1);
while(t--){
cin>>L>>R;
cout<<solve(R)-solve(L-1)<<endl;
}
return 0;
}