[2020牛客暑期多校训练营第七场] H.Dividing 整数分块

题目链接:H.Dividing

题意

给你一个定义:

  1. (1,k)的元组定义为一个Legend Tuple。
  2. 如果 (n, k) 是一个Legend Tuple,那么(n+k,k)也是一个Legend Tuple。
  3. 如果 (n, k) 是一个Legend Tuple,那么(nk,k)也是一个Legend Tuple。

给你N和K,代表着1≤n≤N,1≤k≤K。问你在这个区间有多少个Legend Tuple。

题解

首先我们可以罗列所有的符合条件的Legend Tuple。
(1,1) (2,1) (3,1) (4,1) (5,1) (6,1) (7,1) …(N,1)
(1,2) (2,2) (3,2) (4,2) 。。。。。。。。(N,2)
(1.3) (3,3) (4,3) (6,3) (7,3) 。。。。。。。。
(1,4) (4,4) (5,4) (8,4) (9,4) 。。。。。。。。
.
.
.
.
(1,K) (K,K) (K+1,K) (2K,K) (2*K+1,K) (3K,K+1) (3K+1,K+1)…

通过上面的罗列的表,基本可以看出规律。
其实从第二行开始,我们可以将发现的规律转化为一个公式。
由于K>=1,所以由第一行可知一开始ans+=N。
然后 a n s + = i = 2 K ( N / i + ( N 1 ) / i + 1 ) {ans+=\sum_{i=2}^K{(\lfloor N/i \rfloor+ \lfloor (N-1)/i \rfloor+1)}}
看到这一部分很容易想到用整数分块做。
但很明显我们需要对整数分块的板子进行修改。

ll fenk(int n,int k)
{
	ll ans=0;
	for(int l=2,r;l<=k;l=r+1)
	{
		r=n/(n/l);
		ans+=(r-l+1)*(n/l);
	}
	return ans;
}

我们可以看出整数分块里面(k≤n)才会有结果。否则当l>n时,(n/l)这一项为零,导致分母为零报错。但很显然当K>N时,(1,n+1)~(1,K)这几行只有一种情况,所以答案的值为fenk(n,n)+(K-N)。
其次当分块k<n时,我们可以发现需要修改一些边界条件。

ll fenk(int n,int k)
{
	ll ans=0;
	for(int l=2,r;l<=k;l=r+1)
	{
		r=n/(n/l);
		if(r>k) ans+=(k-l+1)*(n/l);
		else ans+=(r-l+1)*(n/l);
	}
	return ans;
}

然后答案可以确定

ans+=(N==k?fenk(N-1,k-1):fenk(N-1,k)+1;

代码

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<deque>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
using namespace std;
//extern "C"{void *__dso_handle=0;}
typedef long long ll;
typedef long double ld;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pii pair<int,int>

const double PI=acos(-1.0);
const double eps=1e-6;
const ll mod=1e9+7;
const int inf=0x3f3f3f3f;
const int maxn=1e5+10;
const int maxm=100+10;
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

ll fenk(ll n,ll k)
{
	ll ans=0;
	for(ll l=2,r;l<=k;l=r+1)
	{
		r=n/(n/l);
		if(r>=k) ans=(ans+(k-l+1)*(n/l))%mod;
		else ans=(ans+(r-l+1)*(n/l))%mod;//求和
	}
	return ans;
}

int main()
{
	ll N,K;
	scanf("%lld%lld",&N,&K);
	ll ans=0;
	ans=(ans+N)%mod;
	if(N<K) 
	{
		ans=(ans+K-N)%mod;
		K=N;
	}
	ans=((ans+((N==K ? fenk(N-1, K-1):fenk(N-1, K))+fenk(N, K)+K-1))%mod+mod)%mod;
	printf("%lld\n",ans);
}

猜你喜欢

转载自blog.csdn.net/weixin_44235989/article/details/107744839