Uva 11552 Fewest Flops

来源:互联网 发布:苹果6电话录音软件 编辑:程序博客网 时间:2024/05/22 00:42

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 kS2 be the substring of S from + 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 be “uuvuwwuv” and be 4. Then S1 is “uuvu” and has three chunks, but may be rearranged to “uuuv” which has two chunks. Similarly, Smay be rearranged to “vuww”. Then S’, or S1S2, is “uuuvvuww” which is 4 chunks, indeed the minimum number of chunks.

Program Input

The input begins with a line containing (1 ≤ ≤ 100), the number of test cases. The following lines contain an integer 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

25 helloworld7 thefewestflops
OUTPUT
8
10
题意:输入一个正整数k和字符串s,字符串的长度保证为k的整数倍,把s从左到右每k个分为一组,每组之间可以任意排列,但是组与组的先后顺序保持不变,求出重排后整个字符串包含的最小“块”数
思路:dp+贪心,首先相同的字符肯定是放在一起最优,那么对于每段的字符串,中间的所有字母都可以把相同的摆在一起,因此只要考虑前后即可
因为只有前后才有组合的可能,所以定义dp[i][j]为第i块,且和第i - 1块的连接字符为j
先预处理每一段的字母个数,那么状态转移为:如果当前开头字符可以等于j,那么块数相加少1,如果不可以等于,那么就不少1。
#include<cstdio>#include<iostream>#include<cstring>#define inf 0x3f3f3f3fusing namespace std;const int maxn=1005;int t,g,ob[maxn][30],cnt[maxn],ans=inf;int f[maxn][30];char s[maxn];void clear(){memset(ob,0,sizeof(ob));memset(cnt,0,sizeof(cnt));memset(f,inf,sizeof(f));ans=inf;}int main(){int i,j,k,len;scanf("%d",&t);while(t--){clear();scanf("%d%s",&g,s);len=strlen(s);for(i=0;i<len;i+=g)    for(j=i;j<i+g;j++){    if(ob[i][s[j]-'a']==0)cnt[i]++;    ob[i][s[j]-'a']++;}for(i=0;i<26;i++){if(ob[0][i])f[0][i]=cnt[0];if(len==g)ans=min(ans,f[0][i]);}for(i=g;i<len;i+=g)    for(j=0;j<26;j++)        if(ob[i-g][j])            for(k=0;k<26;k++){            if(!ob[i][k])continue;            if(ob[i][j]&&(cnt[i]==1||j!=k))                f[i][k]=min(f[i][k],f[i-g][j]+cnt[i]-1);            else f[i][k]=min(f[i][k],f[i-g][j]+cnt[i]);            if(i+g==len)ans=min(ans,f[i][k]);}printf("%d\n",ans);}}


                                             
0 0