您的位置:首页 > 其它

Find a multiple POJ - 2356 鸽巢原理

2017-04-06 19:38 381 查看
鸽巢原理见《组合数学》第43页应用3 如下图:



原题链接:点击打开链接

Find a multiple

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 7913 Accepted: 3445 Special Judge
Description

The input contains N natural (i.e. positive integer) numbers ( N <= 10000 ). Each of that numbers is not greater than 15000. This numbers are not necessarily different (so it may happen that two or more of them will be equal). Your task is to choose a few of
given numbers ( 1 <= few <= N ) so that the sum of chosen numbers is multiple for N (i.e. N * k = (sum of chosen numbers) for some natural number k).
Input

The first line of the input contains the single number N. Each of next N lines contains one number from the given set.
Output

In case your program decides that the target set of numbers can not be found it should print to the output the single number 0. Otherwise it should print the number of the chosen numbers in the first line followed by the chosen numbers themselves (on a separate
line each) in arbitrary order. 

If there are more than one set of numbers with required properties you should print to the output only one (preferably your favorite) of them.
Sample Input
5
1
2
3
4
1

Sample Output
2
2
3

Source

Ural Collegiate Programming Contest 1999

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>

using namespace std;

const int maxn = 15000 + 10;

int a[maxn], sub[maxn];
int n, m;
int sum[maxn];
int vis[maxn];

void judge()///这里写成函数也是必要,因为有可能后面还有sum[i]相同,但是l,r已经有自己的值了
{ ///用break只能跳出一层循环,也是不可取的 所以只能用函数
int l, r;
vis[0] = 0;///这里是必要的,因为有的sum[i]为0那么直接将这个输出就行了所以要保证vis[0] != -1
///而且不能memset成0 因为那样的话vis[0] 这种情况没法判断了
for (int i = 1; i <= n; i++){
if(vis[sum[i]] == -1)
vis[sum[i]] = i;
else {
l = vis[sum[i]];
r = i;///这里的意思就是没遇到两个相同的余数时
///将当前的赋值为i表示这一次的取余为sum[i]的地方被访问了
///如果上一次已经有值了说明这一次的余数有相等的,即为vis[]里面存的值,
///所以左界是上次存的 即vis[sum[i]] 右界为i
cout << r - l << endl;
//cout << r << endl << l << endl;
for(int i = l+1 ; i <= r ; i++)
cout << a[i] << endl;
return ;
}
}
}

int main()
{
int flag = 0;
int l, r;
while(cin >> n){
l = r = 0;
memset(a, 0, sizeof(a));
memset(sum, 0, sizeof(sum));
memset(vis, -1, sizeof(vis));
for(int i = 1 ; i <= n ; i++){
cin >> a[i];
sum[i] = (sum[i-1] + a[i]) % n;
}
judge();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM 算法 蓝桥杯