zoukankan      html  css  js  c++  java
  • SPOJ:PATHETIC STRINGS(分配问题&贪心)

    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
    ",ans);
        }
        return 0;
    }
     
  • 相关阅读:
    css3 的box-sizing属性理解
    web自定义炫酷字体
    Canvas rontate(旋转) 使用误区
    HTM5 之 Canvas save 、restore 恢复画布状态的理解
    Canvas的quadraticCurveTo 和 bezierCurveTo 画曲线 方法细说
    关于EF的一点小记录
    IIS 发布webservice 需要用户名和密码访问 解决
    【算法笔记】A1060 Are They Equal
    【算法笔记】A1063 Set Similarity
    【算法笔记】B1052 卖个萌
  • 原文地址:https://www.cnblogs.com/hua-dong/p/8971006.html
Copyright © 2011-2022 走看看