首页 > 代码库 > Poj2356Find a multiple鸽巢原理

Poj2356Find a multiple鸽巢原理

  一定存在连续的k个数,使得他们的和能被n整除。设a[i]为前缀和

a[1]%n  ,a[2]%n,...,a[n]%n的值的范围<n,所以有n个数小与n,肯定会出现两个一样的数,表明了,第二个数比第一个数多出来的一部分一定能被n整除。

要注意处理 前缀和中出现0的情况。

#include<iostream>#include<cstdio>#include<cstring>#include<map>#include<vector>#include<stdlib.h>using namespace std;typedef long long LL;int main(){    int n;    int a[22222];    int b[22222];    int vis[22222];    while (cin >> n){        memset(a, 0, sizeof(a));        memset(b, 0, sizeof(b));        memset(vis, 0, sizeof(vis));        for (int i = 1; i <= n; i++)            cin >> a[i], b[i] = a[i];        for (int i = 1; i <= n; i++){            b[i] += b[i - 1]; b[i] %= n;        }        int gg = 0;        for (int i = 1; i <= n;i++)        if (b[i] == 0){            cout << i << endl;            for (int j = 1; j <= i; j++)                cout << a[j] << endl;            gg = 1; break;        }        if (gg) continue;        int flag = 0;        for (int i = 1; i <= n; i++){            if (flag) continue;            if (!vis[b[i]]){                vis[b[i]] = i;            }            else{                cout << i - vis[b[i]] << endl;                for (int j = vis[b[i]]+1; j <= i; j++)                    cout << a[j] << endl;                break;            }        }    }    return 0;}

 

Poj2356Find a multiple鸽巢原理