CF.1416B. Make Them Equal

從冬發表於2020-09-30

題目連結:http://codeforces.com/contest/1416/problem/B

描述:

You are given an array aa consisting of nn positive integers, numbered from 11 to nn. You can perform the following operation no more than 3n3n times:

  1. choose three integers i, j and x (1≤i,j≤n; 0≤x≤10^9);
  2. assign ai:=ai−x⋅i,aj:=aj+x⋅i.

After each operation, all elements of the array should be non-negative.

Can you find a sequence of no more than 3n3n operations after which all elements of the array are equal?

分析:當x=1,i=1時的兩種情況比較特殊,從此入手,先把所有可以加的值加到a[1]上,當a[i]%i==0時,直接加到a[1]即可,若a[i]%i!=0,先與a[1]操作,使a[i]加到為i的倍數,然後再全加到a[1],因為a[i]>=1,所以一定可以完成以上操作

然後令i=1,去使其他數變為平均數。最終操作次數最多是3n-3

#include<bits/stdc++.h>
#define N 10010
#define ll long long
using namespace std;
int n,a[N];
struct nd{
	int l,r,v;
};
vector<nd>ans;
int main(){
	int qt;
	scanf("%d",&qt);
	while(qt--){
		scanf("%d",&n);
		int tot=0;
		ans.clear();
		for(int i=1;i<=n;i++)scanf("%d",&a[i]),tot+=a[i];
		if(tot%n!=0){
			printf("-1\n");continue;
		}
		int x;
		for(int i=2;i<=n;i++){
			int t=a[i]/i;
			if(a[i]%i==0){
				a[i]-=t*i;a[1]+=t*i;
				//cout
				ans.push_back((nd){i,1,t});
			}else{
				x=i-a[i]%i;a[i]+=x;a[1]-=x;
	///			cout<<a[1]<<"***"<<endl;
				ans.push_back((nd){1,i,x});
				x=a[i]/i;a[1]+=a[i];a[i]=0;
				ans.push_back((nd){i,1,x});
			}
		}
		int mid=tot/n;
		for(int i=2;i<=n;i++){
			a[i]=mid;a[1]-=mid;
			ans.push_back((nd){1,i,mid});	
		}
		int len=ans.size();
		printf("%d\n",len);
		for(int i=0;i<len;i++)printf("%d %d %d\n",ans[i].l,ans[i].r,ans[i].v);
	}
	return 0;
}

 

相關文章