P4127 [AHOI2009]同类分布 数位dp + 对状态剪枝

2021/6/12 10:23:44

本文主要是介绍P4127 [AHOI2009]同类分布 数位dp + 对状态剪枝,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

传送门

文章目录

  • 题意:
  • 思路:

题意:

在这里插入图片描述

思路:

比较套路的题,首先也有个明显的状态 f [ p o s ] [ n u m ] [ s u m ] f[pos][num][sum] f[pos][num][sum]表示到了 p o s pos pos位,当前数为 n u m num num,各位数字之和为 s u m sum sum。由于 a , b ≤ 1 e 18 a,b\le1e18 a,b≤1e18,所以显然是不行的。看到整除就可以考虑是否可以通过将第二维取模来优化状态呢?我们发现第三维最多只有 9 ∗ 18 9*18 9∗18个数,所以我们枚举第三维的约数,让后将 n u m num num模上约数即可,这样状态只有 20 ∗ 9 ∗ 18 ∗ 9 ∗ 18 20*9*18*9*18 20∗9∗18∗9∗18个了,再乘上枚举约数 9 ∗ 18 9*18 9∗18,复杂度约为 85030560 85030560 85030560,显然可以过掉。

// Problem: P4127 [AHOI2009]同类分布
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P4127
// Memory Limit: 125 MB
// Time Limit: 3000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")
//#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#include<random>
#include<cassert>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid ((tr[u].l+tr[u].r)>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std;

//void rd_cre() { freopen("d://dp//data.txt","w",stdout); srand(time(NULL)); }
//void rd_ac() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//AC.txt","w",stdout); }
//void rd_wa() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//WA.txt","w",stdout); }

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;

const int N=1000010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;

LL a,b;
int A[20],tot;
int limit;
LL f[20][9*18+10][9*18+10];

LL dp(int pos,int num,int sum,int flag) {
	if(sum>limit) return 0;
	if(pos==0) return num==0&&sum==limit;
	if(f[pos][num][sum]!=-1&&flag) return f[pos][num][sum];
	int x=flag? 9:A[pos];
	LL ans=0;
	for(int i=0;i<=x;i++) {
		ans+=dp(pos-1,(num*10+i)%limit,sum+i,flag||i<x);
	}
	if(flag) f[pos][num][sum]=ans;
	return ans;
}

LL solve(LL x) {
	tot=0;
	while(x) A[++tot]=x%10,x/=10;
	return dp(tot,0,0,0);
}

int main()
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);
	
	//cout<<20*9*18*9*18*9*18<<endl;
	cin>>a>>b;
	LL ans=0;
	for(int i=1;i<=9*18;i++) {
		limit=i; memset(f,-1,sizeof(f));
		ans+=solve(b)-solve(a-1);
	}
	cout<<ans<<endl;


	return 0;
}
/*

*/











这篇关于P4127 [AHOI2009]同类分布 数位dp + 对状态剪枝的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程