๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
โœจ Algorithm

[๋ฐฑ์ค€/C++] 4358๋ฒˆ : ์ƒํƒœํ•™

by nitronium102 2021. 9. 12.

๋ฌธ์ œ

์ƒํƒœํ•™์—์„œ ๋‚˜๋ฌด์˜ ๋ถ„ํฌ๋„๋ฅผ ์ธก์ •ํ•˜๋Š” ๊ฒƒ์€ ์ค‘์š”ํ•˜๋‹ค. ๊ทธ๋Ÿฌ๋ฏ€๋กœ ๋‹น์‹ ์€ ๋ฏธ๊ตญ ์ „์—ญ์˜ ๋‚˜๋ฌด๋“ค์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๊ฐ ์ข…์ด ์ „์ฒด์—์„œ ๋ช‡ %๋ฅผ ์ฐจ์ง€ํ•˜๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค.

์ž…๋ ฅ

ํ”„๋กœ๊ทธ๋žจ์€ ์—ฌ๋Ÿฌ ์ค„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, ํ•œ ์ค„์— ํ•˜๋‚˜์˜ ๋‚˜๋ฌด ์ข… ์ด๋ฆ„์ด ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ์ข… ์ด๋ฆ„๋„ 30๊ธ€์ž๋ฅผ ๋„˜์ง€ ์•Š์œผ๋ฉฐ, ์ž…๋ ฅ์—๋Š” ์ตœ๋Œ€ 10,000๊ฐœ์˜ ์ข…์ด ์ฃผ์–ด์ง€๊ณ  ์ตœ๋Œ€ 1,000,000๊ทธ๋ฃจ์˜ ๋‚˜๋ฌด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.

์ถœ๋ ฅ

์ฃผ์–ด์ง„ ๊ฐ ์ข…์˜ ์ด๋ฆ„์„ ์‚ฌ์ „์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๊ณ , ๊ทธ ์ข…์ด ์ฐจ์ง€ํ•˜๋Š” ๋น„์œจ์„ ๋ฐฑ๋ถ„์œจ๋กœ ์†Œ์ˆ˜์  4์งธ์ž๋ฆฌ๊นŒ์ง€ ๋ฐ˜์˜ฌ๋ฆผํ•ด ํ•จ๊ป˜ ์ถœ๋ ฅํ•œ๋‹ค.

ํ’€์ด

์†Œ์ˆ˜์  ๊ณ ์ •๊ณผ map๋งŒ ์•Œ๋ฉด ๋น ๋ฅด๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ!

01. ๊ณต๋ฐฑ ํฌํ•จ ํ•œ ์ค„์”ฉ ์ž…๋ ฅ

getline(cin, name)

- key๊ฐ€ ์ข… ์ด๋ฆ„, value๊ฐ€ ์ถœํ˜„ ๋นˆ๋„ ์ˆ˜์ธ map์„ ๋งŒ๋“ค์–ด ๊ฐ’์„ ๋„ฃ์–ด์ค€๋‹ค

- ์ „์ฒด ๋นˆ๋„ ์ˆ˜๋„ ํ•˜๋‚˜์”ฉ ์˜ฌ๋ ค์ค€๋‹ค.

 

02. ์†Œ์ˆ˜์  ์ž๋ฆฌ ๊ณ ์ •

cout << fixed;
cout.precision(4); // ์›ํ•˜๋Š” ์†Œ์ˆ˜์  ์ดํ•˜ ์ž๋ฆฟ์ˆ˜

 

#include <iostream>
#include <map>
using namespace std;

int main(){
    string name;
    int total_cnt = 0;
    map<string, double> m;

    while(getline(cin, name)){ // ๊ณต๋ฐฑ ํฌํ•จ ํ•œ ์ค„์”ฉ ์ž…๋ ฅ๋ฐ›๊ธฐ
        m[name]++;
        total_cnt++;
    }

    // ์†Œ์ˆ˜์  ์ž๋ฆฌ ๊ณ ์ •(4์ž๋ฆฌ)
    cout << fixed;
    cout.precision(4);

    for (auto & iter : m){
        cout << iter.first << " " << (iter.second/total_cnt)*100 << "\n";
        // double ์•ˆ ์จ๋„ ๋จ(int -> double ํ˜•๋ณ€ํ™˜)
    }
}

๋Œ“๊ธ€