D. Zero Remainder Array【1400 / 思维 规律】

在这里插入图片描述
https://codeforces.com/problemset/problem/1374/D
模拟做法: TLE了。
大致思路用一个小根堆来存储。

  • 如果堆内为空,说明直接就是合法的直接输出0
  • 否则直接模拟,例如k=5,当2有两个时,第一个2是可以直接加的,但是第二个2就不可以了,我们得走一轮即2+k==2+5以此类推。
#include<bits/stdc++.h>
using namespace std;
const int N=1e5*2+10;
typedef long long int LL;
LL a[N],n,m,t;
int main(void)
{
	scanf("%lld",&t);
	while(t--)
	{
		scanf("%lld%lld",&n,&m);
		for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
		priority_queue<LL,vector<LL>,greater<LL>>heap;
		for(int i=1;i<=n;i++) 
		{
			int temp=(m-a[i]%m);
			if(temp!=m) heap.push( temp );
		}
		LL last=0;
		if(!heap.size())
		{
			cout<<0<<endl;
		    continue;
		}
		while(heap.size())
		{
			auto a=heap.top(); heap.pop();
			if(a<=last) heap.push(a+m);
			last=max(last,a);
		}
		cout<<last+1<<endl;
	}
	return 0;
}

优化的代码用map来看该数有没有出现过,没出现过直接赋值,出现过的话直接加一轮。
注意随时的维护最大的信息

#include<bits/stdc++.h>
using namespace std;
const int N=1e5*2+10;
typedef unsigned long long int LL;
LL a[N],n,m,t;
int main(void)
{
	cin>>t;
	while(t--)
	{
		cin>>n>>m;
		map<LL,LL>mp;
		LL ans=0;
		for(int i=1;i<=n;i++)
		{
			cin>>a[i];
			LL temp=a[i]%m;
			if(!temp) continue;//直接可以整除
			temp=m-temp;
			if(mp.count(temp)==0)//不存在 
			{
				mp[temp]=temp;
				ans=max(ans,temp);
			}
			else//存在了 
			{
				mp[temp]=mp[temp]+m;//直接加一轮 
				ans=max(ans,mp[temp]);
			}
		}
		if(ans) cout<<ans+1<<endl;
		else cout<<ans<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值