POJ 3370

POJ 3370

题意:
万圣节晚上,有c个孩子去要糖,总共有n户人家。但是每个孩子要分一样的糖,所以他们就选取了其中的几家。
求选出人家的编号。
思路:
这是一个鸽巢原理的应用。
设这n户人家的糖数分别为:
A1, A2, A3, … ,An.
对它们取前n项和为:
S1, S2, S3, … , Sn.
对前n项和每项对c取模为:
M1, M2, M3, …, Mn;
其中如果有Mi == 0,那么答案就是从1 到 i。
否则,选取其中Mi == Mk 的i, k.从i + 1到k就是答案。
其中对于Mi和Mk相等,那么一定有以下式子:

Sk - Si (mod c) = 0(mod c)
Sk - Si = (A1 + A2 + A3 + ... + Ai + ... + Ak) - (A1 + A2 + A3 + ... + Ai)
        = Ai+1 + Ai+2 + .... + Ak

以上貌似没有考虑到没有解的情况啊,其实这道题是一定有解的。
以为n >= c,那么一定有大于等于n个的余数,这些余数的范围是从0 ~ c -1.
根据鸽巢原理,那么一定会有起码1个重复的余数。
Code:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<stack>
#include<list>
#include<map>
#include<set>

#define TEST

#define LL long long
#define Mt(f, x) memset(f, x, sizeof(f));
#define rep(i, s, e) for(int i = (s); i <= (e); ++i)
#ifdef TEST
    #define See(a) cout << #a << " = " << a << endl;
    #define See2(a, b) cout << #a << " = " << a << ' ' << #b << " = " << b << endl;
    #define debug(a, s, e) rep(_i, s, e) {cout << a[_i] << ' ';} cout << endl;
    #define debug2(a, s, e, ss, ee) rep(i_, s, e) {debug(a[i_], ss, ee)}
#else
    #define See(a)
    #define See2(a, b)
    #define debug(a, s, e)
    #define debug2(a, s, e, ss, ee)
#endif // TEST

const int MAX = 2e9;
const int MIN = -2e9;
const double eps = 1e-8;
const double PI = acos(-1.0);

using namespace std;

const int N = 100000 + 5;

int v[N];

int read()
{
    char c = getchar();
    while(!isdigit(c)) c = getchar();
    int ret = 0;
    while(isdigit(c))
    {
        ret = ret * 10 + c - '0';
        c = getchar();
    }
    return ret;
}

int main()
{
    int c, n;
    while(~scanf("%d%d", &c, &n))
    {
        if(c == 0 && n == 0)
        {
            return 0;
        }
        Mt(v, 0);
        LL tem = 0;
        bool hasFind = false;
        for(int i = 1; i <= n; ++i)
        {
            int a;
            a = read();
            if(hasFind) continue;
            tem += a;
            int t = tem % c;
            if(!t)
            {
                for(int k = 1; k < i; ++k)
                {
                    printf("%d ", k);
                }
                printf("%d\n", i);
                hasFind = true;
            }
            else
            {
                if(v[t])
                {
                    for(int k = v[t] + 1; k < i; ++k)
                    {
                        printf("%d ", k);
                    }
                    printf("%d\n", i);
                    hasFind = true;
                }
            }
            v[t] = i;
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值