๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜/Code Tree

[์ฝ”๋“œํŠธ๋ฆฌ] TreeMap ์—ฐ์Šต๋ฌธ์ œ

728x90

๋ฌธ์ œ

n๊ฐœ์˜ ๋ช…๋ น์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๊ฐ ๋ช…๋ น์„ ์ˆ˜ํ–‰ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•ด๋ณด์„ธ์š”. ๋ช…๋ น์˜ ์ข…๋ฅ˜๋Š” ํฌ๊ฒŒ 4๊ฐ€์ง€ ์ž…๋‹ˆ๋‹ค.

  • add k v : (k, v) ์Œ์„ treemap์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค. key๊ฐ€ k, value๊ฐ€ v๋ผ๋Š” ๋œป์ž…๋‹ˆ๋‹ค. ์ด๋•Œ ๋งŒ์•ฝ ๋™์ผํ•œ k๊ฐ€ ์ด๋ฏธ ์กด์žฌํ•œ๋‹ค๋ฉด, v๋กœ ๋ฎ์–ด์”๋‹ˆ๋‹ค.
  • remove k : key๊ฐ€ k์ธ ์Œ์„ ์ฐพ์•„ treemap์—์„œ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค. ์ž˜๋ชป๋œ ์ž…๋ ฅ์€ ์ฃผ์–ด์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
  • find k : key๊ฐ€ k์ธ ์Œ์ด treemap์— ์žˆ๋Š”์ง€๋ฅผ ํŒ๋‹จํ•ฉ๋‹ˆ๋‹ค. ์žˆ๋‹ค๋ฉด ํ•ด๋‹นํ•˜๋Š” value๋ฅผ ์ถœ๋ ฅํ•˜๊ณ , ์—†๋‹ค๋ฉด None์„ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.
  • print_list : treemap์— ์žˆ๋Š” ์Œ๋“ค์„ key ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•˜์—ฌ ๊ฐ value ๊ฐ’๋“ค๋งŒ ๊ณต๋ฐฑ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ treemap์ด ๋น„์–ด์žˆ๋‹ค๋ฉด None์„ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

์ž…๋ ฅ ํ˜•์‹

์ฒซ ๋ฒˆ์งธ ์ค„์—๋Š” n์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

๋‘ ๋ฒˆ์งธ ์ค„ ๋ถ€ํ„ฐ๋Š” n๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ ๊ฐ ๋ช…๋ น์ด ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ๊ฐ ๋ช…๋ น์— ์ฃผ์–ด์ง€๋Š” key์™€ value๋Š” ์ „๋ถ€ ์ˆซ์ž์ž…๋‹ˆ๋‹ค. ๋ช…๋ น๋“ค์€ ์ˆœ์„œ๋Œ€๋กœ ์ˆ˜ํ–‰๋˜์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋‹จ, print_list ๋ช…๋ น์€ ์ตœ๋Œ€ 10๋ฒˆ๋งŒ ์ฃผ์–ด์ง„๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋„ ์ข‹์Šต๋‹ˆ๋‹ค.

  • 1 ≤ n ≤ 100,000
  • 1 ≤ ์ฃผ์–ด์ง€๋Š” ์ˆซ์ž ≤ 

์ถœ๋ ฅ ํ˜•์‹

๊ฒฐ๊ณผ๋ฅผ ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

 

๋‚˜์˜ ํ’€์ด

 

#include <iostream>
#include <string>
#include <map>

using namespace std;

int n;
map<int, int> m;

int main() {
    cin >> n;
    for(int i = 0; i < n; i++) {
        string command;
        cin >> command;

        if(command == "add") {
            int k, v;
            cin >> k >> v;
            m[k] = v;
        }
        else if(command == "remove") {
            int k;
            cin >> k;
            m.erase(k);
        }
        else if(command == "find") {
            int k;
            cin >> k;
            if(m.find(k) == m.end())
                cout << "None" << endl;
            else
                cout << m[k] << endl;
        }
        else {
            if(m.empty()) {
                cout << "None" << endl;
                continue;
            }
            map<int, int>::iterator it;
            for(it = m.begin(); it != m.end(); it++)
                cout << it -> second << " ";
            cout << endl;
        }
    }
    return 0;
}

 

 

๋ฌธ์ œ ์ถœ์ฒ˜ ์ฝ”๋“œํŠธ๋ฆฌ
728x90