天天看點

CCF NOI1080. 統計字元 (C++)

1080. 統計字元

題目描述

Johe最近玩起了字元遊戲,規則是這樣的:讀入四行字元串,其中的字母都是大寫的,Johe想列印一個柱狀圖顯示每個大寫字母的頻率。你能幫助他嗎?

輸入

輸入檔案共有4行:每行為一串字元,不超過100個字元。

輸出

與樣例的格式保持嚴格一緻。

樣例輸入

THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.

THIS IS AN EXAMPLE TO TEST FOR YOUR

HISTOGRAM PROGRAM.

HELLO!

樣例輸出

CCF NOI1080. 統計字元 (C++)

資料範圍限制

提示

1.輸出的相鄰字元間有一個空格。

2.最後一行的26個大寫字母每次必須輸出。

C++代碼
#include <iostream>
#include <map>
#include <string>
#include <iterator>
#include <cassert>
#include <cstring>
#include <algorithm>

using namespace std;

int main()
{
    const int max_char_frenquency = 500;  // maximum character frequency
    char charBarGraph[26][max_char_frenquency];  // 'A' to 'Z'
    const int max_lines = 4;
    const int max_num_of_chars_per_line = 100;

    string strText;
    map<char, int> JoheGame;

    for(int i=1; i<=max_lines; i++)
    {
        getline(cin, strText);

        for(unsigned int j=0; j<strText.size() && j<max_num_of_chars_per_line; j++)
        {
            char c = strText[j];
            if (c >= 'A' && c <= 'Z')
            {
                JoheGame[c]++;
            }
        }
    }

    for(int i=0; i<26; i++)    // from 'A' to 'Z': 26 characters
    {
        memset(charBarGraph, ' ', sizeof(charBarGraph));  // default is blank (' ')
    }

    map<char, int>::iterator iter;
    int actual_max_char_frequency = 0;  // actual maximum char frequency 
    int index;  // char index from 0 to 25

    for(iter=JoheGame.begin();iter!=JoheGame.end();iter++)
    {
        actual_max_char_frequency = max(iter->second, actual_max_char_frequency);
        
        index =  int(iter->first - 'A');

        charBarGraph[index][0] = iter->first;  // first char is 'A'..'Z'

        for(int j=1; j<=iter->second; j++)
        {
            charBarGraph[index][j] = '*';  // fill with '*' according to char frequency
        }
    }
    
    // output char bar graph after statistics
    for(int j=actual_max_char_frequency; j>=0; j--) 
    {
        for(int i=0; i<26; i++)
        {
            cout << charBarGraph[i][j] << " ";  // add one blank between two columns 
        }
        cout << endl;
    }

    return 0;
}
           

繼續閱讀