【比赛】USACO21 Jan
文章目录
Dec的时候进了Gold,于是这次只参加了Gold
P7296 [USACO21JAN] Uddered but not Herd G
题意:
给定字符串s,试构造一种小写字母排列p,使得将s划分为若干组,每组字符串均为p的子序列,且使得组数最少,输出最少组数。
保证s长度小于等于1e5且s出现的不同字符不超过二十个
题解:
因为 ∣ p ∣ |p| ∣p∣很小,可以考虑状压DP
正难则反,考虑把每个字符划分为一段
如果相邻两个字母在排列中顺序就把他们合并起来
设 d p [ i ] dp[i] dp[i]表示当前的排列中已经选择了的字母集合
更新时枚举下一个字母的选择
对于在排列中出现过的字母如果在原串中位于当前字母之后
则他们无法合并,产生对答案的贡献
可以先处理出每一对相邻字母数量
记忆化搜索即可
#include<bits/stdc++.h>
using namespace std;
inline int Read(){
int s = 0 , w = 1;
char ch = getchar();
while(ch > '9' || ch < '0'){
if(ch == '-') w = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
s = (s << 1) + (s << 3) + ch - '0';
ch = getchar();
}
return s * w;
}
const int MAXN = 1e5 + 50;
char s[MAXN];
int a[MAXN];
int p[25][25];
int n;
int id[300],tot = 0;
int f[(1 << 21) + 10];
int DP(int ss){
if(ss == (1 << tot) - 1) return 0;
if(f[ss]) return f[ss];
int res = 0;
for(int i = 1 ; i <= tot ; i ++){
if((ss >> (i - 1)) & 1) continue;
int tmp = 0;
for(int j = 1 ; j <= tot ; j ++){
if((ss >> (j - 1)) & 1){
tmp += p[j][i];
}
}
res = max(res,tmp + DP((1 << (i - 1)) | ss));
}
return (f[ss] = res);
}
int main(){
scanf("%s",s + 1);
n = strlen(s + 1);
for(int i = 1 ; i <= n ; i ++){
if(!id[s[i]]) id[s[i]] = ++ tot;
a[i] = id[s[i]];
}
for(int i = 1 ; i + 1 <= n ; i ++){
p[a[i]][a[i + 1]] ++;
}