组合数学 抽屉原理 Poj 2356

来源:互联网 发布:淘宝网 阿里巴巴 编辑:程序博客网 时间:2024/05/18 15:05

先介绍一下抽屉原理,百度百科大法好,特别详细;
https://baike.baidu.com/item/%E6%8A%BD%E5%B1%89%E5%8E%9F%E7%90%86/233776?fr=aladdin&fromid=8942185&fromtitle=%E9%B8%BD%E7%AC%BC%E5%8E%9F%E7%90%86#reference-[1]-19947814-wrap

然后忘了的话看百度百科吧;
poj 2007

Find a multiple
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 8490 Accepted: 3690 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

思路:据说用到鸽笼原理,然后自己也不明白跟鸽笼定理有啥关系,看了一个解释,介绍的很清楚,
定理:给定m个数a1,a2,…,an.则比存在整数k和l(0<=k

#include<cstdio>#include<iostream>#include<cstring>#include<cmath>#include<algorithm>using namespace std;#define N 150000int a[N];int sum[N];int main(){    int n;    while(~scanf("%d",&n))    {        for(int i=1; i<=n; i++)        {            scanf("%d",&a[i]);        }        int pos=-1;        sum[0]=0;        for(int i=1; i<=n; i++)        {            sum[i]=(sum[i-1]+a[i])%n;            if(sum[i]==0)            {                pos=i;            }        }        if(pos>0)        {            printf("%d\n",pos);            for(int i=1;i<=pos;i++)            {                printf("%d\n",a[i]);            }        }        else        {            int x,y;            for(int i=1;i<=n;i++)            {                for(int j=1;j<=i;j++)                {                    if(sum[i]-sum[j]==0)                    {                       x=i;                       y=j;                       break;                    }                }            }            printf("%d\n",x-y);            for(int k=y+1;k<=x;k++)            {                printf("%d\n",a[k]);            }        }    }}
原创粉丝点击