「杂题乱刷」CF1759F

题目链接

CF1759F All Possible Digits(luogu)

CF1759F All Possible Digits(codeforces)

题意简述

有一个长度为 \(n\)\(p\) 进制数,你需要求出至少通过几次操作才可以让 \(0 \sim p - 1\)\(p\) 个数字都至少出现过一遍(包括中间过程)。

解题思路

我们很容易就能发现答案是具有单调性的,也就是说,如果操作 \(x\) 次是合法的,那么操作 \(x + 1\) 次也一定是合法的。

然后我们还可以发现一个性质,就是答案一定小于 \(p\),因为每一次操作都会使最后一位数字变化,所以操作 \(p - 1\) 次最后一位数字会变化 \(p\) 次,因此这个性质是正确的。

于是我们可以直接二分最少的操作次数即可,这里我选择使用分讨数字操作后是否进位的方式来进行二分。

参考代码

#include<bits/stdc++.h>
using namespace std
//#define map unordered_map
#define forl(i,a,b) for(register long long i=a;i<=b;i++)
#define forr(i,a,b) for(register long long i=a;i>=b;i--)
#define forll(i,a,b,c) for(register long long i=a;i<=b;i+=c)
#define forrr(i,a,b,c) for(register long long i=a;i>=b;i-=c)
#define lc(x) x<<1
#define rc(x) x<<1|1
//#define mid ((l+r)>>1)
#define cin(x) scanf("%lld",&x)
#define cout(x) printf("%lld",x)
#define lowbit(x) (x&-x)
#define pb push_back
#define pf push_front
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define endl '\n'
#define QwQ return 0;
#define ll long long
#define ull unsigned long long
#define lcm(x,y) x/__gcd(x,y)*y
#define Sum(x,y) 1ll*(x+y)*(y-x+1)/2
#define aty cout<<"Yes\n";
#define atn cout<<"No\n";
#define cfy cout<<"YES\n";
#define cfn cout<<"NO\n";
#define xxy cout<<"yes\n";
#define xxn cout<<"no\n";
#define printcf(x) x?cout<<"YES\n":cout<<"NO\n";
#define printat(x) x?cout<<"Yes\n":cout<<"No\n";
#define printxx(x) x?cout<<"yes\n":cout<<"no\n";
ll t;
ll n,m;
ll a[110],b[110];
bool check(ll Mid)
{
	forl(i,0,n)
		a[i]=b[i];
	if(Mid+a[n]>=m)
	{
		map<ll,ll>mp;
		forl(i,1,n)
			mp[a[i]]++;
		ll pd=0;
		Mid-=m-a[n];
		ll lst=a[n]-1;
		a[n]=0,a[n-1]++;
		if(n-1==0)
			pd=1;
		forr(i,n-1,1)
		{
			if(a[i]==m)
			{
				a[i]=0,a[i-1]++;
				if(i==1)
					pd=1;
			}
		}
		if(pd)
			forl(i,0,n)
				mp[a[i]]++;
		else
			forl(i,1,n)
				mp[a[i]]++;
		while(mp[lst])
			lst--;
		return lst<=Mid;
	}
	else
	{
		map<ll,ll>mp;
		forl(i,1,n)
			mp[a[i]]++;
		ll lst=m-1;
		while(mp[lst])
			lst--;
		ll nxt=0;
		while(mp[nxt])
			nxt++;
//		cout<<Mid<<":"<<lst-a[n]<<endl;
		if(nxt<a[n])
			return 0;
		return max(0ll,lst-a[n])<=Mid;
	}
}
void solve()
{
	cin>>n>>m;
	forl(i,1,n)
		cin>>a[i],b[i]=a[i];
	ll L=0,R=m;
	while(L<R)
	{
		ll Mid=(L+R)/2;
		if(check(Mid))
			R=Mid;
		else
			L=Mid+1;
	}
	cout<<L<<endl;
}
int main()
{
	IOS;
	t=1;
	cin>>t;
	while(t--)
		solve();
	QwQ;
}
posted @ 2024-05-23 15:13  wangmarui  阅读(1)  评论(0编辑  收藏  举报