均分纸牌

 原题链接:https://www.luogu.org/problem/show?pid=1031

简单的贪心+模拟。

对于这道题,如果你能想到平均数,那就已经成功了一半了。 可以知道,最终的结果是每一堆上放的纸牌的数量都是平均数,那我们只需要处理那些数量不等于平均数的堆就好了。

平均数的想法还是很容易能想出来的,毕竟纸牌数量一定,而堆数也一定,那要平均分成的话肯定是平均数了。

读入每一堆的数量后,把这个数用平均数减掉,得到一个新数,这个新数就是我们要对这个堆改变的课本的数量,它可以是负的。

随后判断它是不是0,不是就把后一位的加过来,累加器+1,是的话就跳过。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cctype>
 5 #define maxn 100005
 6 using namespace std;
 7 inline int read(){
 8     char c;
 9     int num = 0;
10     bool flag = false;
11     while ((c=getchar())== ' ' || c == '
' || c == '
');
12     if (c == '-')
13         flag = true;
14     else    
15         num = c - '0';
16     while (isdigit(c = getchar()))
17         num = num * 10 + c - '0';
18     return (flag? -1 : 1) * num;
19 }
20 int n;
21 int a[maxn];
22 int sum;
23 int ans;
24 int main(){
25     n = read();
26     for (int i=1;i<=n;i++){
27         a[i] = read();
28         sum += a[i];
29     }
30     sum /= n;
31     for (int i=1;i<=n;i++)
32         a[i] -= sum;
33     for (int i=1;i<=n;i++){
34         if (a[i] != 0){
35             a[i+1] += a[i];
36             a[i] = 0;
37             ans++;
38         }
39     }
40     cout << ans << endl;
41     return 0;
42 }
原文地址:https://www.cnblogs.com/OIerShawnZhou/p/7507983.html