总结-小技巧

扫码查看

尺取法

尺取法可以\(O(n)\)解决:对给定的一个序列,在序列中寻找包含全部需求的,长度最小的一段子序列一类问题

LuoguP1381 单词背诵

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int a = (b); a <= (c); ++a)
#define nR(a,b,c) for(register int a = (b); a >= (c); --a)
#define Fill(a,b) memset(a, b, sizeof(a))
#define Swap(a,b) ((a) ^= (b) ^= (a) ^= (b))

#define ON_DEBUGG

#ifdef ON_DEBUGG

#define D_e_Line printf("\n-----------\n")
#define D_e(x) std::cout << (#x) << " : " <<x << "\n"
#define FileOpen() freopen("in.txt", "r", stdin)
#define FileSave() freopen("out.txt", "w", stdout)
#define Pause() system("pause")
#include <ctime>
#define TIME() fprintf(stderr, "\nTIME : %.3lfms\n", clock() * 1000.0 / CLOCKS_PER_SEC)

#else

#define D_e_Line ;
#define D_e(x) ;
#define FileOpen() ;
#define FilSave ;
#define Pause() ;
#define TIME() ;

#endif

struct ios {
    template<typename ATP> ios& operator >> (ATP &x) {
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-') f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x *= f;
        return *this;
    }
}io;

using namespace std;

template<typename ATP> inline ATP Min(ATP a, ATP b) {
    return a < b ? a : b;
}
template<typename ATP> inline ATP Max(ATP a, ATP b) {
    return a > b ? a : b;
}

const int N = 100007;
const unsigned int MOD = 2999993;
const unsigned int base = 13331;

char str[N];
unsigned long long a[N], b[N];
int vis[MOD];
bool mark[MOD];
inline long long Hash(char *str) {
    int len = strlen(str + 1);
    unsigned long long val = 0;
    R(i,1,len){
        val = (val * base + (unsigned long long)(str[i] - 'a')) % MOD;
    }
    return (val + MOD) % MOD;
}
int main() {
    int n;
    io >> n;
    R(i,1,n){
        scanf("%s", str + 1);
        a[i] = Hash(str);
        mark[a[i]] = true;
    }
    int m;
    io >> m;
    int ans = 0, ans2 = 0x7fffffff;
    R(i,1,m){
        scanf("%s", str + 1);
        b[i] = Hash(str);
        if(mark[b[i]] && !vis[b[i]]){
            ++ans;
            vis[b[i]] = 1;
        }
    }
    if(ans == 0){
        printf("0\n0");
        return 0;
    }
    int l = 1, r = 1, tot = ans;
    Fill(vis, 0);
    while(1){
        if(!tot){
            while(!mark[b[l]]) ++l;
            if(l > m) break;
            ans2 = Min(ans2, r - l);
            if(vis[b[l]] == 1) ++tot;
            if(vis[b[l]] >= 1) --vis[b[l]], ++l;
        }
        else{
            if(r > m) break;
            if(mark[b[r]]){
                if(!vis[b[r]]) --tot;
                ++vis[b[r]];
            }
            ++r;
        }
    }
    printf("%d\n%d", ans, ans2);
    return 0;
}
02-12 14:30
查看更多