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
- Sicily 1901. Beans
- Beans
- Beans
- 企业Beans Enterprise Beans
- 企业Beans Enterprise Beans
- java beans
- Java Beans
- beans.xml
- XML Beans
- Managed Beans
- spring beans
- hdu2845 Beans
- spring beans
- beans.xml
- beans配置
- HDU2845--Beans
- beans.xml
- Managed Beans
- log4j和web.xml配置webAppRootKey 的问题
- js 中 String.replace() 的使用
- JavaScript中常见的数组操作函数及用法
- mybatis中的#和$的区别
- Android【Layout_weight的深刻理解】
- Sicily 1901. Beans
- 从关系型数据库到非关系型数据库
- make
- js跳转到锚点(jQuery动画滚动到锚点)
- Oracle中对XMLType的简单操作(extract、extractvalue)
- Assets/NGUI/Scripts/UI/UILabel.cs(398,33): error CS0506: `UILabel.relativeSize': cannot override inh
- UIColor RGB颜色对照表
- web.xml中webAppRootKey
- 百度地图计算两点之间距离