1. 程式人生 > >SPOJ:PATHETIC STRINGS(分配問題&貪心)

SPOJ:PATHETIC STRINGS(分配問題&貪心)

har ini algorithm space NPU nbsp 問題 cte rain

Problem statement:

A string is said to be “PATHETIC” if all the characters in it are repeated the same number of times. You are given a string of length n, what is the minimum number of changes required to make a string “PATHETIC”. The string has only lower case letters and you can change any letter to any other letter.

Input Format
The first line contains an integer T, the number of test cases. This is followed by T test cases each containing 1 line:
Each testcase consists of a string composed of lowercase letters.


Output Format

For each testcase, print in a new line the minimum number of changes required.

Constraints
1 ≤ T ≤ 1370
1 ≤ n ≤ 1991

Sample Input :

2

bbaccaaa

ccaacb

Output:

2

1

題意:給定字符串,問這樣才能讓字符串裏的每個字符的次數相同,每次可以把任意的字符變成任意的字符,求最小操作次數。

思路:把字符想成箱子,那麽最多有26個箱子,枚舉箱子數X,然後不難知道相應的變化數,更新最小值:

當前箱子大於X,那麽從大到小排序,把X後面的幾個箱子的貨物搬出來,如果前面X個箱子的物體大於N/X,那麽多的要搬出來。然後把搬出來的轉移到前面X個裏面小於N/X的地方。

當前箱子小於等於X,那麽大的搬出來給小的。

#include<cmath>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int num[27];
char c[2010];
bool cmp(int a,int b){
    return a>b;
}
int main()
{
    int T,L,i,j,ans,tot;
    scanf("%d",&T);
    while(T--){
        scanf("%s",c+1); 
        L=strlen(c+1); ans=L-1;
        for(i=1;i<=26;i++) num[i]=0;
        for(i=1;i<=L;i++) num[c[i]-a+1]++;
        sort(num+1,num+26+1,cmp);
        for(tot=1;tot<=26;tot++) if(num[tot]==0)  break; tot--;
        for(i=1;i<=26;i++){
            if(L%i==0){
                int tmp=0;
                if(tot>i){
                    for(j=1;j<=i;j++) if(num[j]>L/i) tmp+=num[j]-L/i; 
                    for(j=tot;j>i;j--) tmp+=num[j];
                } 
                else{
                    for(j=1;j<=tot;j++)  if(num[j]>L/i) tmp+=num[j]-L/i;
                }
                if(tmp<ans) ans=tmp; 
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}
 

SPOJ:PATHETIC STRINGS(分配問題&貪心)