鸽巢原理(入门) 之 poj 2356

来源:互联网 发布:plc用什么软件编程 编辑:程序博客网 时间:2024/06/05 04:22
//  [3/27/2014 Sjm]/*鸽巢原理: 若 n+1 个物体被放进 n 个盒子, 那么至少有一个盒子包含两个或者更多的物体解决 poj 2356:问题简化: 有 n 个数字,a1, a2, a3..., an, 找出连续的数字串,使数字串的和可整除 n。若存在,则输出数字串个数,并依次输出数字串;否则,输出0。分析:依次求出 sum[1] = a1, sum[2] = sum[1]+a2, sum[3] = sum[2]+a3..., sum[n] = sum[n-1]+an1) 若存在 0 == sum[i]%n, 即 数字串个数为 i, 依次输出 a1, a2, ..., ai 即为答案。2)否则,由于 sum[i]%n 值的区间为 {1, 2, ..., n-1}, 区间个数为 n-1, 而共有 n 个数,   故而,必然存在 l 和 r (注: 1<=l<R<=N),使 sum[l]%n == sum[r]%n   即可推出:sum[l] = x*n + (sum[l]%n)sum[r] = y*n + (sum[r]%n)两式相减:sum[r] - sum[l] = (y-x)*n故而:下标为 l+1, l+2, ..., r 的这一数字串的和可整除 n。*/
#include <iostream>#include <cstdlib>#include <cstdio>#include <queue>using namespace std;const int MAX_N = 10000;int N, arr[MAX_N], mySum[MAX_N + 1];struct node{int x, y;friend bool operator <(const node &n1, const node &n2) {if (n1.y == n2.y) return n1.x > n2.x;else return n1.y > n2.y;}};priority_queue<node> pri_que;void Solve(){int myl, myr;node n1 = pri_que.top();pri_que.pop();while (pri_que.size()){node n2 = pri_que.top();pri_que.pop();if (n1.y == n2.y) {myl = n1.x;myr = n2.x;printf("%d\n", myr - myl);for (int i = myl; i < myr; i++)printf("%d\n", arr[i]);return;}n1 = n2;}printf("0\n");}int main(){//freopen("input.txt", "r", stdin);//freopen("output.txt", "w", stdout);scanf("%d", &N);node n;n.x = n.y = 0;pri_que.push(n);for (int i = 0; i < N; i++){scanf("%d", &arr[i]);mySum[i + 1] = (mySum[i] + arr[i]) % N;n.x = i + 1, n.y = mySum[i + 1];pri_que.push(n);}Solve();return 0;}
0 0
原创粉丝点击