CF.1416B. Make Them Equal

题目链接: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;
}

 

©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页