Sicily 1901. Beans

来源:互联网 发布:北京地铁网络取票 编辑:程序博客网 时间:2024/06/10 07:54

题目
这里写图片描述

大意
现在有N堆豆子,要从这N堆豆子中选连续的若干堆,选取的豆堆豆数总和为Sum,现在要使Sum%P≤K,问如何取可以使Sum/P最大。

思路
利用前缀和数组Sum[i]快速计算和。
中间一段连续的豆数为Sum[p2] - Sum[p1],那么有:
0≤(Sum[p2] - Sum[p1])%P≤K;
即(Sum[p2]%P - Sum[p1]%P + P)%P≤K;
我们可以事先算出所有的Sum[pn]%P,然后对此进行排序,如果对P取模的值不同,则按照对P取模的值由小到大排序;否则,按照原来的位置序号由小到大排序。
然后利用单调队列即可。


在Sicily中,此题有坑。
注意输出一定要令Ans为%I64d,%d、%lld、%I32d都不行。

代码

#include <stdio.h>#include <algorithm>#include <string.h>using namespace std;const unsigned int MAXN = 1000005;struct Node {    int mod, pos;    Node(int mod = 0, int pos = 0) {        this->mod = mod;        this->pos = pos;    }};int Sum[MAXN];int Ans;int Num[MAXN], Q[MAXN], N, P, K;Node Nodes[MAXN];char Text[MAXN * 10];bool cmp(const Node & N1, const Node & N2) {    if (N1.mod != N2.mod) return N1.mod < N2.mod;    else return N1.pos < N2.pos;}void Input() {    long S = 0;    gets(Text);    int pos = 0, k = 1;    while (Text[pos] != '\0') {        if (Text[pos] == ' ') {            Num[k++] = S;            S = 0;        }        else S = S * 10 + Text[pos] - '0';        pos++;    }    Num[k] = S;}int main() {    int CaseNum, NowCase = 1;    scanf("%d\n", &CaseNum);    while (CaseNum--) {        scanf("%d %d %d\n", &N, &P, &K);        memset(Q, 0, sizeof(int) * (N + 5));        memset(Nodes, 0, sizeof(Node) * (N + 5));        Input();        Sum[0] = 0;        for (int i = 1; i <= N; i++) {            Sum[i] = Sum[i - 1] + Num[i];            Nodes[i].mod = Sum[i] % P;            Nodes[i].pos = i;        }        sort(Nodes, Nodes + N + 1, cmp);        int head = 1, tail = 0;        Ans = -1;        Q[head] = 0;        for (int i = 0; i <= N; i++) {            while (head <= tail && Nodes[i].pos < Nodes[Q[tail]].pos) tail--;            Q[++tail] = i;            while (head <= tail && Nodes[i].mod - Nodes[Q[head]].mod > K) head++;            if (head == tail) continue;            long temp = (Sum[Nodes[i].pos] - Sum[Nodes[Q[head]].pos]) / P;            if (temp > Ans) Ans = temp;        }        printf("Case %d: %I64d\n", NowCase++, Ans);    }    return 0;}
0 0
原创粉丝点击