天天看點

HDOJ 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): 97201    Accepted Submission(s): 37153

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

5
green
red
blue
red
red
3
pink
orange
pink
0
        

Sample Output

red
pink
  
  

  
  

  
  
   一 分析
  
  
   	這道題要解決的問題很明确,也很簡單,就是要統計每個字元串出現的次數,然後找出現最多的那一個。
  
  
   二 算法
  
  
   	每次加入新的元素與之前出現的每一個進行一次比較,如果這個color之前出現過,這個color的數量就+1,如果我們仔細思考可以發現這個方法和我們人工統計的方法其實沒有什麼差別。
  
  
   三 資料結構
  
  
   	确定了算法以後,我們就要根據我們設計的算法構造資料結構,根據上面算法的要求,我們需要一個能存放字元串的數組,和一個能存放次數的數組,并且這兩個數組能通過其數組下标一一準确對應起來。
  
  

  
  
   
//

   
//  main.cpp

   
//  1004

   
//

   
//  Created by 張嘉韬 on 16/1/9.

   
//  Copyright © 2016年 張嘉韬. All rights reserved.

   
//

   



   
#include <iostream>

   
#include <cstring>

   
using namespace std;

   
int main(int argc, const char * argv[]) {

   
    //freopen("/Users/zhangjiatao/Desktop/input.txt","r",stdin);

   
    int n;

   
    while(cin>>n)

   
    {

   
        if(n==0) break;

   
        char color[1001][16];

   
        int counter[1001];

   
        memset(counter,0,sizeof(counter));

   
        for(int i=1;i<=n;i++)

   
        {

   
            cin>>color[i];

   
            counter[i]=1;

   
        }

   
        for(int i=1;i<=n-1;i++)

   
        {

   
            for(int j=i+1;j<=n;j++)

   
            {

   
                if(strcmp(color[i],color[j])==0)

   
                    counter[i]++;

   
            }

   
        }

   
        int max,maxnum;

   
        max=0,maxnum=0;

   
        for(int i=1;i<=n;i++)

   
        {

   
            if(counter[i]>max)

   
            {

   
                max=counter[i];

   
                maxnum=i;

   
            }

   
        }

   
        cout<<color[maxnum]<<endl;

   
    }

   
    return 0;

   
}

   

   
   
    四 總結
   
   
    	1.上邊的代碼用了跟簡單的一種方法,先把所有的字元串儲存起來,再跟其之前的所有字元串相比較,最後再統計最大的次數。
   

        

繼續閱讀