P1031 均分纸牌
描述
见链接
分析
此题归类于模拟和贪心的,起初想用暴力模拟的,写出来非常复杂而且最后RE了非常尴尬。
后来看了看题解,就成了倒数字了,很简练有点抽象。
代码
大佬正确的
#include<iostream>
#include<cstdio>
using namespace std;
int a[10010];
int n;
int sum=0,x=0,to1=0;
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
sum+=a[i];
}
x=sum/n;
for(int i=1;i<=n;i++) a[i]=a[i]-x;
for(int i=1;i<=n;i++)
{
if(a[i]==0) continue;
a[i+1]=a[i]+a[i+1];
to1++;
}
cout<<to1;
return 0;
}
自己的留念…
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int big(int cot[],int n){
int cur=-1,ret=0;
for(int i=0;i<n;i++){
if(cot[i]>cur){
cur = cot[i];
ret = i;
}
}
return ret;
}
bool eql(int cot[],int n){
for(int i=1;i<n;i++) if(cot[i]!=cot[i+1]) return false;
return true;
}
int acu(int cot[], int beg, int en){
int sum = 0;
for(int i=beg;i<=en;i++) sum+=cot[i];
return sum;
}
int main(){
int n,sum=0;
cin>>n;
int cot[102];
for(int i=1;i<=n;i++){
cin>>cot[i];
sum+=cot[i];
}
int avg = sum/n;
int times,bar,lloss,rloss;
times=0;
while(!eql(cot,n)){
bar = big(cot,n+1);
cout<< "bar : "<<bar<< " "<<cot[bar] <<endl;
if(bar!=1){
lloss = avg*(bar - 1)-acu(cot,1,bar-1);
if(lloss>0){
cot[bar-1]+=lloss;
cot[bar] -=lloss;
times++;
}
}
if(bar!=n){
rloss = avg*(n-bar)-acu(cot,bar+1,n);
if(rloss>0){
times++;
cot[bar] -= rloss;
cot[bar+1]+=rloss;
}
}
}
cout<<times;
return 0;
}