1. 程式人生 > >【HUD】1004 : Let the Balloon Rise

【HUD】1004 : Let the Balloon Rise

Let the Balloon Rise

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 133383    Accepted Submission(s): 52671

Problem Description Contest time again! How excited it is to see balloons floating around. But to tell you a secret, the judges' favorite time is guessing the most popular problem. When the contest is over, they will count the balloons of each color and find the result.This year, they decide to leave this lovely job to you.   
Input Input contains multiple test cases. Each test case starts with a number N (0 < N <= 1000) -- the total number of balloons distributed. The next N lines contain one color each. The color of a balloon is a string of up to 15 lower-case letters.A test case with N = 0 terminates the input and this test case is not to be processed.  
Output For each case, print the color of balloon for the most popular problem on a single line. It is guaranteed that there is a unique solution for each test case.  
Sample Input
 
   
    5greenredblueredred3pinkorangepink0
    
    
   
      
    
Sample Output
 
    
     redpink
     
    
   
      
    
Author WU, Jiazhi  
Source ZJCPC2004  
Recommend JGShining   |   We have carefully selected several similar problems for you:  
1008
  1005  1009  1019  1021   
 

思路:

 
1.由於scanf("%d",&n)的返回值為成功輸入的數目,cin的返回值為輸入變數的記憶體地址。所以不能作為檢測是n否為0的標準,此處的方法是在迴圈中判0並跳出,也可以使用scanf(cin>>n&&n)作乘操作判斷結果;

2.具體方法是建立一個字串陣列,C++的庫為<string>,string型別支援直接判等操作,元件陣列後一邊輸入一邊進行檢查。

3.每次輸入之後檢查與之前輸入的字串是否相等並進行比較計數,然後得出出現次數最多的字串,將其儲存在pop變數中,如果n==1那麼讓pop賦值為僅有的一個元素。

4.由於題目的特殊性:所以不需要減去已經檢查過的字串(結果相同),也不需要對出現次數相等字串操作,因此節約了很多程式碼。


程式碼:

#include <cstdio>
#include <cstring>
#include <string>
using namespace std;

int main()
{
    string str[1001]; //up to 1000 kinds of colour
    int n,max,count;
    string pop;
    while(cin>>n)
    {
        if(n==0)break;
        max=0;
        for(int i=0; i<n; i++)
        {

            count=0;
            cin>>str[i]; //input one color string
            if(n==1)pop=str[i];
            for(int j=0; j<i; j++)
            {

                if(str[i]==str[j])
                    {
                        count++;
                    }
            }

            if(count>max)
            {
                max=count;
                pop=str[i];
            }

        }

        cout<<pop<<endl;
    }





    return 0;
}