B. Make Array Good codeforces 1762B

55 篇文章 1 订阅

题目大意:给出一个n个数的数组a,每次操作可以使任意一个数加上一个不大于他本身的数x,问能否使任意两个数都有一方能被整除

1<=n<=1e5;1<=ai<=1e9

思路:我们先把数组从小到大排序,发现只要每相邻两个数能整除,那任意两个数都可以,所以

//#include<__msvc_all_public_headers.hpp>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 5;
pair<ll,int> a[N];
int main()
{
	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(false);
	int t;
	cin >> t;
	while (t--)
	{
		int n;
		cin >> n;
		for (int i = 1; i <= n; i++)
		{
			cin >> a[i].first;
			a[i].second = i;//记录排序前的编号
		}
		sort(a + 1, a + n + 1);
		queue<pair<int, ll > >ans;
		for (int i = 2; i <= n; i++)
		{
			if (a[i].first < a[i - 1].first)
			{//如果小于上一个数,就变成上一个数
				ans.push(make_pair(a[i].second, a[i - 1].first - a[i].first));
				a[i].first = a[i - 1].first;
			}
			else if(a[i].first%a[i-1].first!=0)
			{//如果大于且没法整除上一个数,就变成最近的倍数
				ans.push(make_pair(a[i].second, (a[i].first / a[i - 1].first + 1) * a[i - 1].first - a[i].first));
				a[i].first = (a[i].first / a[i - 1].first + 1) * a[i-1].first;
			}
		}
		cout << ans.size() << endl;
		while (!ans.empty())
		{
			cout << ans.front().first << " " << ans.front().second << endl;
			ans.pop();
		}
	}
	return 0;
}

如果当前数大于前一个数,那就让这个数变成离上一个数最近的倍数,这样+的x一定小于a[i-1],就i更不会大于a[i],且数字也不会修改大过2e9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

timidcatt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值