天天看点

2356 Find a multiple 抽屉原理 给定n个数,求其中的任意一个子集满足集合中的每个元素值加和正好是n的倍数

Find a multiple

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 2547 Accepted: 1109 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
      
一个经典的问题:给定n个数,求其中的任意一个子集满足集合中的每个元素值加和正好是n的倍数。刚开始怎么也没有思路,因为n很大,直接搜索显然是不行的。后来在组合数学书上找到了这个例题(晕,之前白看了,居然把这个经典的题目都给忘了),是抽屉原理的典型应用。
  假定n个数为a1,a2,...,an,前n项和分别是S1、S2、...、Sn,那么如果有一个Si模n是0,就是答案,否则,n个数模n的余数只能在1到n - 1之间,把余数作为抽屉,显然n个数放到n - 1个抽屉里面,肯定有两个数余数相等,这样取它们的差就得到了结果,算法复杂度是O(n)的。
      
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int a[11001],vis[11001],s[11001];
int main()
{
    int n;
    while(scanf("%d",&n)==1)
    {
        int pos,len=0;
        memset(vis,0,sizeof(vis));
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            s[i]=(s[i-1]+a[i])%n;
            if(len) continue;//已经找到解
            int mod=s[i];
            if(mod==0)
            {
                pos=1,len=i;
                continue;
            }
            if(vis[mod]==0)
            {
                vis[mod]=i;
            }
            else
            {
                len=i-vis[mod];
                pos=vis[mod]+1;
            }
        }
        printf("%d/n",len);
        for(int i=pos;i<pos+len;i++) printf("%d/n",a[i]);
    }
    return 0;
}
      

继续阅读