Subsequences Summing to Sevens
时间限制: 1 Sec 内存限制: 64 MB提交: 55 解决: 29
[ 提交][ 状态][ 讨论版]
题目描述
Farmer John's N cows are standing in a row, as they have a tendency to do from time to time. Each cow is labeled with a distinct integer ID number so FJ can tell them apart. FJ would like to take a photo of a contiguous group of cows but, due to a traumatic childhood incident involving the numbers 1…6, he only wants to take a picture of a group of cows if their IDs add up to a multiple of 7.
Please help FJ determine the size of the largest group he can photograph.
Please help FJ determine the size of the largest group he can photograph.
输入
The first line of input contains N (1≤N≤50,000). The next N lines each contain the N integer IDs of the cows (all are in the range 0…1,000,000).
输出
Please output the number of cows in the largest consecutive group whose IDs sum to a multiple of 7. If no such group exists, output 0.
You may want to note that the sum of the IDs of a large group of cows might be too large to fit into a standard 32-bit integer. If you are summing up large groups of IDs, you may therefore want to use a larger integer data type, like a 64-bit "long long" in C/C++.
You may want to note that the sum of the IDs of a large group of cows might be too large to fit into a standard 32-bit integer. If you are summing up large groups of IDs, you may therefore want to use a larger integer data type, like a 64-bit "long long" in C/C++.
样例输入
7
3
5
1
6
2
14
10
样例输出
5
提示
In this example, 5+1+6+2+14 = 28.
又是一道前缀和的问题,没有修改插入,只是静态的查询,用前缀和进行预处理简直给力。
通过预处理前缀和mod7,放到sum数组中,如果两个位置的sum相等,即他们取余7之后的结果相同,则他们的差,也就是后面减去前面,剩下的部分,取余7等于0。
遍历取最长的就好了。
#include <set>
#include <map>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#define pi acos(-1.0)
#define maxn (101000 + 50)
#define mol 1000000009
#define inf 0x3f3f3f3f
#define Lowbit(x) (x & (-x))
using namespace std;
typedef long long int LLI;
int a[maxn],sum[maxn];
int vis[10],n,re;
int main() {
memset(vis,-1,sizeof(vis));
int n;
while(scanf("%d",&n)!=EOF){
int tmp;
for(int i=1;i<=n;i++){
scanf("%d",&tmp);
sum[i] = (sum[i-1] + tmp)% 7;
}
int re = 0;
for(int i=1;i<=n;i++){
if(vis[sum[i]] == -1){
vis[sum[i]] = i;
}
else re = max(re , i - vis[sum[i]]);
}
printf("%d\n",re);
}
}