Find a multiple POJ - 2356 鸽巢原理

鸽巢原理见《组合数学》第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


#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值