Dreamoon and Strings CodeForces - 477C (字符串dp)

大意: 给定字符串$s$, $p$, 对于$0\le x\le |s|$, 求$s$删除$x$个字符后, $p$在$s$中的最大出现次数.

显然答案是先递增后递减的, 那么问题就转化求最大出现次数为$y$时, 求$S$所需要删除的最少字符数.

先暴力O(n^2)求出以每个字符开头匹配完一个$p$后的最小右端点, 然后$dp$即可.

#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#include <bitset>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc (o<<1)
#define rc (lc|1)
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl '\n'
#define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;})
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;}
//head



const int N = 2e3+10;
int n, m;
char s[N], p[N];
int nxt[N], ans[N], dp[N][N];

int main() {
	scanf("%s%s", s+1, p+1);
	n = strlen(s+1), m = strlen(p+1);
	REP(i,1,n) {
		int now = 1;
		nxt[i] = N-1;
		REP(j,i,n) {
			if (s[j]==p[now]) ++now;
			if (now>m) {nxt[i]=j;break;}
		}
	}
	memset(dp,0x3f,sizeof dp);
	REP(i,0,n) dp[i][0] = 0;
	REP(i,1,n) {
		REP(j,1,n) dp[i][j] = min(dp[i][j], dp[i-1][j]);
		REP(j,1,n) if (dp[i-1][j-1]!=INF&&nxt[i]<=n) {
			dp[nxt[i]][j] = min(dp[nxt[i]][j], dp[i-1][j-1]+nxt[i]-i+1-m);
		}
	}
	REP(i,1,n) if (dp[n][i]!=INF) ans[dp[n][i]] = i;
	REP(i,1,n) ans[i] = max(ans[i], ans[i-1]);
	REP(i,1,n) ans[i] = min(ans[i], (n-i)/m);
	REP(i,0,n) printf("%d ", ans[i]);hr;
}

猜你喜欢

转载自www.cnblogs.com/uid001/p/10919801.html
今日推荐