洛谷 P3131 [USACO16JAN]子共七Subsequences Summing to Sevens

题目描述

Farmer John's NN 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 \ldots 616, 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.

给你n个数,求一个最长的区间,使得区间和能被7整除

输入输出格式

输入格式:

 

The first line of input contains NN (1 \leq N \leq 50,0001N50,000). The next NN

lines each contain the NN integer IDs of the cows (all are in the range

0 \ldots 1,000,00001,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.

 

输入输出样例

输入样例#1: 复制
7
3
5
1
6
2
14
10
输出样例#1: 复制
5

说明

In this example, 5+1+6+2+14 = 28.

思路:前缀和+二分答案。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,l,r,mid;
int num[50010],sum[50010];
bool judge(){
    for(int i=0;i<=n-mid;i++)
        if((sum[i+mid]-sum[i])%7==0)    return true;
    return false;
}
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",&num[i]),sum[i]=sum[i-1]+num[i];
    l=1;r=n;
    while(l<=r){
        mid=(l+r)/2;
        if(judge())    l=mid+1;
        else r=mid-1;
    }
    cout<<l-1;
}
80

思路:求出前缀和mod7,然后遍历,如果拥有相同的余数,说明这个区间是可以被7整除的记录。

 

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define MAXN 50010
using namespace std;
int n;
int pri[10],v[10];
int a[MAXN],sum[MAXN];
int main(){
    scanf("%d",&n);
    sum[0]=0;
    for(int i=1;i<=n;i++)
        scanf("%lld",&a[i]),sum[i]=(sum[i-1]+a[i])%7;
    for(int i=1;i<=n;i++){
        if(!v[sum[i]])
            v[sum[i]]=i,pri[sum[i]]=i;
        else    pri[sum[i]]=i;
    }
    int ans=-1;
    for(int i=0;i<7;i++){
        if(!v[i])    continue;
        ans=max(ans,pri[i]-v[i]);
    }
    printf("%d\n",ans);
}

 

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define MAXN 50010
using namespace std;
int n;
int pri[10],v[10];
int a[MAXN],sum[MAXN];
int main(){
    scanf("%d",&n);
    sum[0]=0;
    for(int i=1;i<=n;i++)
        scanf("%lld",&a[i]),sum[i]=(sum[i-1]+a[i])%7;
    for(int i=1;i<=n;i++){
        if(!v[sum[i]])
            v[sum[i]]=i,pri[sum[i]]=i;
        else    pri[sum[i]]=i;
    }
    int ans=-1;
    for(int i=0;i<7;i++){
        if(!v[i])    continue;
        ans=max(ans,pri[i]-v[i]);
    }
    printf("%d\n",ans);
}

 

 

 

 

posted @ 2017-11-19 22:17  一蓑烟雨任生平  阅读(190)  评论(0编辑  收藏  举报