poj 2356 Find a multiple【抽屉原理】

来源:互联网 发布:阿里云备案拍照要求 编辑:程序博客网 时间:2024/05/04 02:18

Find a multiple
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 8197 Accepted: 3559 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整除(区间长度可以为1),如果不存在输出-1,存在的话任选一种结果输出,先输出区间长度,再输出区间元素;
思路:
不清楚抽屉原理的话,模拟着做下来也不会错,有趣的是这道题不会输出-1这个结果(省赛选拔赛时坑了我们好久,类似的题而已,考察的就是这个永远不会输出-1这个知识点)。因为n个数取余,但是放在1~n的区间内,必定至少存在两个数取余后结果一样,既然存在余数相同,那么在这个余数相同区间范围就一定可以整除n。这种题需要好好想想,这道可能不太难,但是比赛的时候类似这种数学题应该很多;

#include<cstdio>#include<cstring>#include<algorithm>#include<vector>#define max_n 10010typedef long long LL;using namespace std;int a[max_n];int main(){    int n;    while(~scanf("%d", &n))    {        vector<int> v[max_n];        bool flag=false;        int sum=0,cnt,id;        for(int i=1;i<=n;i++)        {            scanf("%d",&a[i]);            sum+=a[i];            cnt=sum%n;            v[cnt].push_back(i);            if(cnt==0 && !flag) //特判一下             {                flag=true;                id=i;            }        }        if(flag)        {            printf("%d\n",id);            for(int i=1;i<=id;i++)                printf("%d\n",a[i]);        }        else        {            for(int i=1;i<=n;i++)            {                if(v[i].size()>1)//判断余数相等                 {                    int st=v[i][0];                    int end=v[i][1];                    printf("%d\n",end-st);//任选一个输出                     for(int j=st+1;j<=end;j++)                        printf("%d\n",a[j]);                    break;                }            }        }    }    return 0;}