首页 技术 正文
技术 2022年11月11日
0 收藏 715 点赞 2,415 浏览 1013 个字

  • 题意:有一个长度为\(n\)的数组,找一段最长子数组,使得其元素和为\(x\),如果存在,输出子数组的长度,否则输出\(-1\).

  • 题解:这题我们要从元素和\(sum\)来考虑,首先,如果原数组的所有元素都被\(x\)整除,那么条件不成立.

    ​ 假如原数组的\(sum\)不被\(x\)整除,那么长度就为\(n\),如果被\(x\)整除,那么我们贪心来想,从前和从后来找第一个\(a[i]\)%\(x\ne0\)的位置,然后比较求个最长即可.

  • 代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <vector>
    #include <map>
    #include <set>
    #include <unordered_set>
    #include <unordered_map>
    #define ll long long
    #define fi first
    #define se second
    #define pb push_back
    #define me memset
    const int N = 1e6 + 10;
    const int mod = 1e9 + 7;
    const int INF = 0x3f3f3f3f;
    using namespace std;
    typedef pair<int,int> PII;
    typedef pair<ll,ll> PLL;int t;
    int n,x;
    int a[N];int main() {
    ios::sync_with_stdio(false);cin.tie(0);
    cin>>t;
    while(t--){
    int sum=0;
    bool ok=0;
    cin>>n>>x;
    for(int i=1;i<=n;++i){
    cin>>a[i];
    sum+=a[i];
    if(a[i]%x!=0) ok=1;
    }
    if(!ok){
    cout<<-1<<endl;
    continue;
    }
    if(sum%x!=0){
    cout<<n<<endl;
    continue;
    }
    int f=n;
    int b=0;
    for(int i=1;i<=n;++i){
    if(a[i]%x!=0){
    f=i;
    break;
    }
    }
    for(int i=n;i>=1;--i){
    if(a[i]%x!=0){
    b=i;
    break;
    }
    }
    cout<<max(n-f,b-1)<<endl;
    } return 0;
    }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295