7.14 考试总结

· · 个人记录

只有最后两道题错了嘻嘻

数字选择2

思路

  1. 最大子数列和的计算

    我们用前缀和来计算。每个位置的 i,以 i 结尾的最大子数列的和就是 sum_i-minn,其中 minn 是 sum_0 到 sum_{i-1} 的最小值。

  2. 统计合法区间数量

    在已知最大子数列和 maxx 之后,再循环一遍,记录位置 pos。如果 sum_i-minn==maxx,那么就说明以 i 结尾的序列存在一个合法区间,所以就可以更新区间数量和最短长度。

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=1e6+10;
int n,a[maxn],sum[maxn];
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    int minn=0;
    int maxx=-1e18;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        sum[i]=sum[i-1]+a[i];
        maxx=max(sum[i]-minn,maxx);
        minn=min(sum[i],minn);
    }
    minn=sum[0];
    int cnt=0;
    int pos=1;
    int minn_len=1e9;
    for(int i=1;i<=n;i++){
        if(sum[i]-minn==maxx){
            cnt++;
            int l=pos+1;
            int r=i;
            minn_len=min(minn_len,r-l+1);
        }
        if(sum[i]<minn){
            minn=sum[i];
            pos=i;
        }
    }
    cout<<maxx<<endl<<cnt<<" "<<minn_len; 
    return 0;
}

数字选择3

闲话

嘤嘤嘤,输出 99 有 38 分,但是我只试到了 95,最后也就弄了个 24 分。。。。。。

题意

给定一个长度为 n 的序列,求所有连续子数列的和模 100 的最大值。

一定要注意一点:负数取模需转化为非负数!!!

思路

  1. 前缀和的处理

    先统计前缀和数组 sum。每个前缀和都要进行模 100 处理并调整为非负数(范围 [0,99])。

  2. 桶

    使用桶数组 tong 来记录已遍历前缀和模 100 的值。这里有个重点,就是 tong_0 默认为 1,也就是标记了。

  3. for 循环枚举

    对于每个位置 r,我们可以枚举所有合法的值 [0,99]。如果 tong_i 被标记过,那么当前这个子数列的和就是:

tmp = (sum_r - i) \bmod 100

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=1e6+10;
int n,a[maxn],sum[maxn],ans;
int tong[maxn];
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        sum[i]=sum[i-1]+a[i];
        sum[i]=(sum[i]%100+100)%100;
    }
    int maxx=0;
    tong[0]=1;
    for(int r=1;r<=n;r++){
        for(int i=0;i<=99;i++){
            if(tong[i]){
                int tmp=sum[r]-i;
                tmp=(tmp%100+100)%100;
                maxx=max(maxx,tmp);
            }
        }
        tong[sum[r]]=1;
    }
    cout<<maxx;
}