Niu Ke Practice 70-B. Piece together

Topic link

Meaning of the title: Find the subsequence in the smallest substring of the string as "puleyaknoi".

Solution: Define nxt[i][j]: the nearest position of the character'a'+j after the i-th character, and then find it violently.

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<queue>
#include<utility>
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
inline int read();
inline long long readl();
inline void write(int x,int ch);
inline void writel(ll x,int ch);

const int maxn=2e5+7;
string st="puleyaknoi";
string s;
int n,nxt[maxn][26];
signed main() {
	int test=read();
	
	while(test--) {
		cin>>s;
		n=s.size();s=" "+s;
		memset(nxt,0,sizeof nxt);
		for(int i=0;i<26;++i) nxt[n+1][i]=-1;
		for(int i=n;i>=1;--i) {
			for(int j=0;j<26;j++) nxt[i][j]=nxt[i+1][j];
			nxt[i][s[i]-'a']=i;
		}
		int ans=1e9;
		for(int i=1;i<=n;++i){
			if(s[i]==st[0]) {
				int pos=0,now=nxt[i][st[pos++]-'a'];
				while(now!=-1&&pos<10){
					now=nxt[now][st[pos++]-'a'];
				}
				if(now!=-1&&pos==10)
				ans=min(ans,now-i+1);
			}
		}
		if(ans!=1e9) printf("%d\n",ans);
		else puts("-1"); 
	} 
}
inline void writel(long long x,int ch) {
	if(x<0) {
		putchar('-');
		x=-x;
	}
	if(x>9) {
		writel(x/10,0);
	}
	putchar(x%10+'0');
	if(ch)
		printf("\n");
	return;
}
inline void write(int x,int ch) {
	if(x<0) {
		putchar('-');
		x=-x;
	}
	if(x>9) {
		write(x/10,0);
	}
	putchar(x%10+'0');
	if(ch)
		printf("\n");
	return;
}
inline long long readl() {
    long long x=0,f=1;
    char ch=getchar();
    while(ch>'9'||ch<'0') {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9') {
        x=x*10+ch-'0';
        ch=getchar();
    }
    return x*f;
}
inline int read() {
    int x=0,f=1;
    char ch=getchar();
    while(ch>'9'||ch<'0') {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9') {
        x=x*10+ch-'0';
        ch=getchar();
    }
    return x*f;
}


 

Guess you like

Origin blog.csdn.net/qq_44132777/article/details/108831179