poj 2356 Find a multiple【鸽巢原理 模板应用】

Find a multiple
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6651   Accepted: 2910   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开始的某一段数字对n取余等于0的时候,需要找一个yu[i]和yu[j]相等,采用类似哈希的方式。

代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <algorithm>
#define N 10000+100

using namespace std;

int a[N];
int sum[N];
int yu[N];

struct node
{
	bool k;
	int pos;

}q[N];


int main()
{
	int n;
	int i, j;
	int left, right;

	while(~scanf("%d", &n))
	{
		bool flag1=false;
        bool flag2=false;

		for(i=0; i<n; i++){
			scanf("%d", &a[i] );
			if(i==0) sum[i]=a[i];
			else sum[i]=sum[i-1]+a[i];
		}
		left=0;
		memset(q, 0, sizeof(q));

		for(i=0; i<n; i++){
			yu[i]=sum[i]%n;
			if(yu[i]==0){
				flag1=true; right=i; break;
			}
			else{
				if(q[yu[i]].k ){
					flag2=true;
					left=q[yu[i]].pos; right=i; break;
				}else{
					q[yu[i]].k=true; q[yu[i]].pos=i;
				}
			}
		}
		if(flag1){
			printf("%d\n", right+1 );
			for(i=0; i<=right; i++){
				printf("%d\n", a[i] );
			}
		}
		else if(flag2){
            printf("%d\n", right-left );
            for(i=left+1; i<=right; i++){
				printf("%d\n", a[i] );
			}
		}
	}
	return 0;
}

 

posted @ 2015-07-21 08:25  我喜欢旅行  阅读(160)  评论(0编辑  收藏  举报