Problem F
FEWEST FLOPS
A common way to uniquely encode a string is by replacing its consecutive repeating characters (or “chunks”) by the number of times the character occurs followed by the character itself. For example, the string “aabbbaabaaaa” may be encoded as “2a3b2a1b4a”. (Note for this problem even a single character “b” is replaced by “1b”.)
Suppose we have a string S and a number k such that k divides the length of S. Let S1 be the substring of S from 1 to k, S2 be the substring of S from k + 1 to 2k, and so on. We wish to rearrange the characters of each block Si independently so that the concatenation of those permutations S’ has as few chunks of the same character as possible. Output the fewest number of chunks.
For example, let S be “uuvuwwuv” and k be 4. Then S1 is “uuvu” and has three chunks, but may be rearranged to “uuuv” which has two chunks. Similarly, S2 may be rearranged to “vuww”. ThenS’, or S1S2, is “uuuvvuww” which is 4 chunks, indeed the minimum number of chunks.
Program Input
The input begins with a line containing t (1 ≤ t ≤ 100), the number of test cases. The following t lines contain an integer k and a string S made of no more than 1000 lowercase English alphabet letters. It is guaranteed that k will divide the length of S.
Program Output
For each test case, output a single line containing the minimum number of chunks after we rearrange S as described above.
INPUT
2
5 helloworld
7 thefewestflops
OUTPUT
8 10
题意:一个字符串中,每k个分成一组,你可以随意调整一组中的顺序,相邻的相同字符可以算成一个权值,问最后的最小值是多少。
思路:dp[i][j]表示前i组最后一个字母为j时的最小权值。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s[1010];
int dp[1010][30],best[1010],num[26],INF=1e9;
int main()
{
int T,t,i,j,k,n,m,len,l,r,ret;
scanf("%d",&T);
for(t=1;t<=T;t++)
{
scanf("%d",&m);
scanf("%s",s+1);
len=strlen(s+1);
n=len/m;
best[0]=0;
for(j=0;j<26;j++)
dp[0][j]=1e9;
for(i=1;i<=n;i++)
{
l=1+(i-1)*m;r=i*m;
memset(num,0,sizeof(num));
ret=0;
for(j=l;j<=r;j++)
{
if(num[s[j]-'a']==0)
ret++;
num[s[j]-'a']++;
}
for(j=0;j<26;j++)
dp[i][j]=INF;
if(ret==1)
{
k=s[l]-'a';
dp[i][k]=min(best[i-1]+1,dp[i-1][k]);
}
else
for(j=0;j<26;j++)
{
if(num[j]>0)
{
dp[i][j]=best[i-1]+ret;
for(k=0;k<26;k++)
if(num[k]>0 && k!=j)
dp[i][j]=min(dp[i][j],dp[i-1][k]+ret-1);
}
else
dp[i][j]=INF;
}
best[i]=INF;
for(j=0;j<26;j++)
best[i]=min(best[i],dp[i][j]);
}
printf("%d\n",best[n]);
}
}
最少块数字符串编码

本文介绍了一种字符串编码问题,目标是最小化经过特定分组和字符重组后的字符串中的重复块数量。通过动态规划方法求解,实现了字符串的有效编码。
431

被折叠的 条评论
为什么被折叠?



