Codeforces Round 907 (Div. 2) (E)找规律

1891E - Brukhovich and Exams 

        题意:给定长度为n的数组 a ,定义当gcd(a_{i} , a_{i +1}) = 1时价值为1,其余价值为0。现能够将数组中k个数字变为0(gcd(0 , x) = gcd(x ,0) = x)。求价值总和最小值。

        思路:对于一个不包含1的连续gcd = 1 的序列来说,例如:(3x  , 3 , 5 , 7 , 9 , 11 , 11y)此时总价值为4,我们如果按照顺序变为0,那么每一次操作能够使得价值减少1。这么做无疑是最浪费的,于是发现我们只需要将偶数位(5 , 9)变为0,那么序列变成了(3x , 3 , 0 ,7 , 0 , 11 , 11y)。如此就能够使得价值减少4。因此这么做能够有两次机会使得每次变为0的操作价值额外减少1。因此对于这种序列来说,我们有偶数位个数的机会使得一次操作价值额外减少1。

        对于连续的1的序列而言,例如(x , 1 , 1 , 1 , 1 , 1 , y)。同理按照顺序变为0,每一次操作能够使得价值减少1。但是需要注意到当我们把最后一个1变为0以后,它与右边的数同样变成了gcd != 1的情况。此时能够将价值额外减少1。那么对于该序列而言,我们可以通过整个1序列长度的操作数使得价值额外减少1。需要注意到 :例如序列(1 , 1 , 1 , 1 , 1 , x)我们无法额外将价值减少1。同样的,对于序列(1 , 1 , 1,  1 ,1)而言,第一次操作无法使得价值减少1,然后每一次操作价值减少1,因此需要特殊处理。

        综上,非特殊情况下,每一次操作至少能够使得价值减少1,然后我们将价值额外减少1的操作数进行排序,再由小到大花费这些操作数使得价值最少即可。

        

// Problem: E. Brukhovich and Exams
// Contest: Codeforces - Codeforces Round 907 (Div. 2)
// URL: https://codeforces.com/contest/1891/problem/E
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define pb push_back
#define x first
#define y second 
#define endl '\n'
const LL maxn = 4e05+7;
const LL N=1e05+10;
const LL mod=1e09+7;
typedef pair<int,int>pl;
priority_queue<LL , vector<LL>, greater<LL> >t;
priority_queue<LL> q;
LL gcd(LL a, LL b){
	return b > 0 ? gcd(b , a % b) : a;
}

LL lcm(LL a , LL b){
	return a / gcd(a , b) * b;
}
void solve() 
{
	int n , k;
	cin>> n >> k;	
	int a[n];
	int f = 1;
	for(int i = 0 ; i < n ; i ++){
		cin>>a[i];
		if(a[i] != 1)
			f = 0;
	}
	int ans = 0;
	for(int i = 1 ; i < n ; i ++){
		if(gcd(a[i - 1] , a[i]) == 1){
			ans++;
		}
	}
	vector<int>b;
	for(int l = 0 , r = 0 ; l < n ; l = r + 1){
		r = l;
		if(a[l] == 1){
			continue;
		}
		while(r < n - 1 && a[r + 1] != 1 && gcd(a[r] , a[r + 1]) == 1){
			r += 1;
		}
		int t = (r - l) / 2;
		for(int i = 0 ; i < t; i ++){
			b.pb(1);
		}
	}
	for(int l = 0 , r = 0 ; l <n ; l = r + 1){
		r = l;
		if(a[l] != 1){
			continue;
		}
		while(r < n - 1 && a[r + 1] == 1){
			r += 1;
		}
		if(l != 0 && r != n - 1)//首尾不存在额外的
			b.pb(r - l + 1);
	}
	if(f)
		ans++;
	ans -= k;
	sort(b.begin() , b.end());
	for(auto x : b){
		if(k >= x){
			k -=x;
			ans -= 1;
		}
	}
	cout<<max(ans , 0)<<endl;
}            
int main() 
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cout.precision(10);
    int t=1;
	cin>>t;
    while(t--)
    {
    	solve();
    }
    return 0;
}

        

        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值