Uva 11552 Fewest Flops

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

2
5 helloworld
7 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 0x3f3f3f3f
using 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);
	}
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值