Careercup

2014-05-07 15:17

题目链接

原题:

Given an array of n elements (a1,a2,..ai,...,an). You are allow to chose any index i and j, such that (i!=j) and allow to perform increment operation on ai = ai+1 and decrements operation on aj = aj - 1 infinite number of times. How many maximum number of elements you can find that have same number.

题目:给定一个长度为n的整数数组。每次允许你选取其中两个元素,对一个+1,对另一个-1。如果允许你执行任意多次这样的操作,问你至多能把多少个元素变成同一个数?

解法:第一次看这个题目还看不到懂,但想通了以后发现就是解题几乎就是一句话的事情。每次进行这样的操作时,所有元素加起来的总和一直保持不变,所以只要看看总和能否被n整除。如果能整除,则n个数都会变成一样。否则,只能得到n - 1个一样的数,剩下一个不一样。最后,注意取模运算对于负数的处理。

代码:

 1 // http://www.careercup.com/question?id=6407924087783424
 2 #include <iostream>
 3 #include <vector>
 4 using namespace std;
 5 
 6 inline int mod(int x, int y)
 7 {
 8     return x % y >= 0 ? x % y : y - (y - x) % y;
 9 }
10 
11 int main()
12 {
13     vector<int> v;
14     int n;
15     int i;
16     int sum;
17     
18     while (cin >> n && n > 0) {
19         v.resize(n);
20         for (i = 0; i < n; ++i) {
21             cin >> v[i];
22         }
23         
24         sum = 0;
25         for (i = 0; i < n; ++i) {
26             sum = mod(sum + v[i], n);
27         }
28         cout << (sum ? n - 1 : n) << endl;
29         v.clear();
30     }
31     
32     return 0;
33 }
原文地址:https://www.cnblogs.com/zhuli19901106/p/3713896.html