PKU 2356 Find a multiple

2014-8-1
 
Language:
                                                                                                                                 Find a multiple
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 5942   Accepted: 2585   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
 
/*
此題的判斷方法是用抽屜原理
此題一定有解,不存在輸出0的結果!

證明如下

我們可以依次求出a[0],a[0]+a[1],a[0]+a[1]+a[2],......,a[0]+a[1]+a[2]...+a[n];

假設分別是sum[0],sum[1],sum[2],......,sum[n]

如果在某一項存在是N的倍數,則很好解,即可直接從第一項開始直接輸出答案

但如果不存在,則sum[i]%N的值必定在[1,N-1]之間,又由於有n項sum,有抽屜原理:

 把多於n個的物體放到n個抽屜裏,則至少有一個抽屜裏有2個或2個以上的物體。

則必定有一對i,j,使得sum[i]%N=sum[j]%N,其中i!=j,不妨設j>i

則(sum[j]-sum[i])%N=0,故sum[j]-sum[i]是N的倍數

則只要輸出從i+1~j的所有的a的值就是答案

其實做法可以有兩個方向,一個是判斷餘數是否爲0,有0直接輸出就好,沒0在判斷sum[]餘數相等的情況,然後輸出
另一個方向是出來輸出一個數據的情況直接輸出就好,其他的都找餘數相等就行,然後找到就直接輸出結果
一:
#include<stdio.h>
#include<string.h>
int main()
{
  int sum[1001000],flag[10010],a[10010],str[10010];
  int n,i,j,t;
  while(scanf("%d",&n)!=EOF)
  {
    memset(sum,0,sizeof(sum));
    memset(flag,0,sizeof(flag));
    for(i=1;i<=n;i++)
      scanf("%d",&a[i]);
    for(i=1;i<=n;i++)
    {
          sum[i]=sum[i-1]+a[i];
          t=sum[i]%n;
          if(t==0)     //餘數是0,輸出就好 
           {
              printf("%d\n",i);
              for(j=1;j<=i;j++)
               printf("%d\n",a[j]);
               break;
           }
           else             //餘數不是0,標記餘數,沒標記的就標記爲1,如果已經被標記過,說明找到了 
           {
             if(flag[t]==0)
               {
                  flag[t]=1;
                  str[t]=i;
               }
             else
             {
                printf("%d\n",i-str[sum[i]%n]);
                for(j=str[sum[i]%n]+1;j<=i;j++)
                  printf("%d\n",a[j]);
                  break;
             }   
           }
     }         
  }    
    return 0;
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章