Codeforces Round #825 (Div. 2)

本文解析了三道算法竞赛题目:使两个数组相等的最少操作数、构造满足条件的数组及寻找符合条件的子数组数量。提供了清晰的思路与C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A

Make A Equal to B

题意:给你长度为n的a,b数组,其中只含0和1,有两种操作:(1)将某元素反转(2)将数组任意排列。问最少需要多少次操作使得a等于b

思路:我们用cnt记录 a[i] != b[i] 的次数,那么经过cnt次操作一定可以使a等于b,但不一定是最优;用cnta,cntb分别记录a,b中1的个数,那么经过| cnta - cntb |操作可以让a,b中0,1个数相同,再用一次排列操作即可让a等于b,总操作数为| cnta - cntb |+1;只需要对这两种情况取一个最小值即可。

#include <bits/stdc++.h>
#define lowbit(x) x&(-x)
#define ios std::ios::sync_with_stdio(false);cin.tie(0),cout.tie(0)
#define PII pair<int,int>
typedef long long ll;
const int N=110;
const int inf=0x3f3f3f3f;

using namespace std;
int n;
int a[N],b[N];
void solve()
{
	cin>>n;
	int cnt=0,cnta=0,cntb=0;
	for(int i=1;i<=n;i++) 
	{
		cin>>a[i];
		cnta+=(a[i]==1);
	}
	for(int i=1;i<=n;i++) 
	{
		cin>>b[i];
		cntb+=(b[i]==1);
		if(a[i]!=b[i]) cnt++;
	}
	cout<<min(abs(cnta-cntb)+1,cnt)<<'\n';
}
int main()
{
	//ios;
	int _t=1;
	cin>>_t;
	while(_t--) solve();
	system("pause");
	return 0;
}

B

Playing with GCD

题意:给定长度为n的数组a,问是否存在n+1长度的数组b使得a[i]= gcd ( b[i], b[i+1])

思路:首先我们来看bi需要满足什么性质,b[i]需要含有因数a[i]和a[i+1],即b[i]=c*x,其中x为a[i]和a[i+1]的最小公倍数,我们再看系数c应取多少,因为b[i],b[i+1]的系数含有公因子的话会影响到最大公因数ai,所以令系数全取1,此时b数组一定最优,但不一定符合题意,最后直接for循环判断一下这样的b数组是否满足题目要求即可。

#include <bits/stdc++.h>
#define lowbit(x) x&(-x)
#define ios std::ios::sync_with_stdio(false);cin.tie(0),cout.tie(0)
#define PII pair<int,int>
typedef long long ll;
const int N=1e5+10;
const int inf=0x3f3f3f3f;

using namespace std;
int n;
int a[N],b[N];
void solve()
{
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	a[0]=1;a[n+1]=1;
	for(int i=1;i<=n+1;i++)
	{
		b[i]=a[i]*a[i-1]/gcd(a[i],a[i-1]);
	}
	for(int i=1;i<=n;i++)
	{
		if(a[i]!=gcd(b[i],b[i+1]))
		{
			puts("NO");
			return ;
		}
	}
	puts("YES");
}
int main()
{
	//ios;
	int _t=1;
	cin>>_t;
	while(_t--) solve();
	system("pause");
	return 0;
}

C

Good Subarrays (Easy Version)

题意:给定长度为n的数组a,定义好区间为区间内元素都满足a[i]>=j,其中j为区间元素间的下标(下标从1开始),问有多少好区间。

思路:对于左端点l,暴力搜索其能到达的右端点r,统计以l作为左端点的区间个数。对于l+1,只需要从上一次扩展到的右端点继续向右扩展即可,因为它满足单调性。

#include <bits/stdc++.h>
#define lowbit(x) x&(-x)
#define ios std::ios::sync_with_stdio(false);cin.tie(0),cout.tie(0)
#define PII pair<int,int>
typedef long long ll;
const int N=2e5+10;
const int inf=0x3f3f3f3f;

using namespace std;
int n;
int a[N];
void solve()
{
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	a[n+1]=-inf;
	ll ans=0;
	int last=1;
	for(int l=1;l<=n;l++)
	{
		for(int r=last;r<=n+1;r++)
		{
			if(a[r]<r-l+1)
			{
				ans+=r-l;
				last=r;
				break;
			}
		}
	}
	cout<<ans<<'\n';
}
int main()
{
	//ios;
	int _t=1;
	cin>>_t;
	while(_t--) solve();
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值