洛谷 P1031 [NOIP 2002 提高组] 均分纸牌
很明显的贪心题
EaCode:
#include<iostream>
#include<algorithm>
using namespace std;
int a[110];
int main(){
int N, avg = 0, ans = 0;
cin >> N;
for(int i = 1; i <= N; i++){
cin >> a[i];
avg += a[i];
}
avg /= N;
for(int i = 1; i <= N; i++){
if(a[i] > avg){
int x = a[i] - avg, l = i - 1, r = i + 1, pos = 0;
while(x && l >= 1){
if(a[l] < avg){
int c = avg - a[l];
if(c >= x){
x = 0;
a[l] += x;
a[i] -= x;
}else{
x -= c;
a[l] += c;
a[i] -= c;
}
pos = l;
}
l--;
}
if(pos){
//cout << pos << endl;
ans += i - pos;
}
pos = 0;
while(x && r <= N){
//cout << "d";
if(a[r] < avg){
int c = avg - a[r];
if(c >= x){
x = 0;
a[r] += x;
a[i] -= x;
}else{
x -= c;
a[r] += c;
a[i] -= c;
}
pos = r;
}
r++;
}
if(pos){
//cout << pos << endl;
ans += pos - i;
}
}
}
cout << ans;
return 0;
}
交上去就拿了20分,还是不够贪。。
然后换思路,从左往右,如果小于平均值,从下一个拿,如果大于平均值,给下一个。
AcCode:
#include<iostream>
using namespace std;
int main() {
int N, sum = 0, ans = 0;
cin >> N;
int a[N+1];
for(int i = 1; i <= N; i++) {
cin >> a[i];
sum += a[i];
}
int average = sum / N;
for(int i = 1; i <= N; i++) {
if(a[i] != average) {
ans++;
a[i+1] += a[i] - average;
}
}
cout << ans;
return 0;
}