Source: Huawei OJ
1 //nameBeautyDegree.cpp: Defines the entry point of the console application. 2 //3 4#include"stdafx.h"5#include <iostream>6#include <stdlib.h>7#include <string>8#include <map>9 using namespacestd;Ten //Bubble Sort One voidSortint*array,size_t num) A { - size_t i,j,temp; - for(i=num;i>1; i--) the for(j=0; j<i-1; j + +){ - if(array[j]<array[j+1]){ -temp=Array[j]; -array[j]=array[j+1]; +array[j+1]=temp; - } + } A } at //Calculate the beauty of a name - intNamevalue (Char*name) - { -map<Char,int> myMap;//number of occurrences of a letter -map<Char,int>:: iterator ite; -size_t Size=strlen (name);//the length of the name inUnsignedintI//For Loop - intchvalue[ -];//number of occurrences of a character to intk= -;//Beautiful degree + intNvalue=0;//the beauty of the name - //iterate through the characters in the name, inserting the characters and the number of occurrences into the Mymap the for(i=0; i<size;i++){ *Ite=Mymap.find (Name[i]); $ if(ite!=mymap.end ())Panax Notoginsengite->second+=1; - Else theMymap.insert (pair<Char,int> (Name[i],1)); + } A //get the number of occurrences of all characters theIte=Mymap.begin (); + for(i=0; I<mymap.size (); i++) - { $Chvalue[i]=ite->second; $ite++; - } - //sort the number of occurrences of all characters the sort (chvalue,mymap.size ()); - //Calculate the beauty of a nameWuyi for(i=0; I<mymap.size ()-1; i++) {//I traverse the number of mymap.size ()-1, because the last character is a line break thenvalue+= (Chvalue[i]) *K; -k--; Wu } - returnNvalue; About } $ intMain () { -UnsignedintN; -Unsignedinti; -cin>>n;//Enter number of names A if(n<=0)//number less than 0, return + return 0; the intch; -Ch=getchar ();//receive carriage return character $ Charname[Ten][ -];//Store n Names the //Receive name the for(i=0; i<n;i++) the { theFgets (Name[i], -, stdin);//receives the name, takes the carriage return as the end sign, simultaneously also sends the carriage return to the name, the attention handles off - } in //Print the beauty of each name the for(i=0; i<n;i++) theCout<<namevalue (Name[i]) <<endl;//Call Function Namevalue () About return 0; the}
Programming Exercises: The beauty of the name