์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[๋ฐฑ์ค€(BOJ)] 1620๋ฒˆ: ๋‚˜๋Š”์•ผ ํฌ์ผ“๋ชฌ ๋งˆ์Šคํ„ฐ ์ด๋‹ค์†œ (Hash, C++)

PROGRAMMING/Algorithm

by koharin 2021. 1. 29. 13:35

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

๐Ÿ–จ ์ž…์ถœ๋ ฅ


  • ์ž…๋ ฅ

    • ์ฒซ์งธ์ค„: ๋„๊ฐ์— ์ˆ˜๋ก๋œ ํฌ์ผ“๋ชฌ ๊ฐœ์ˆ˜(N), ๋‹ค์†œ์ด๊ฐ€ ๋งž์ถฐ์•ผ ํ•˜๋Š” ๋ฌธ์ œ ๊ฐœ์ˆ˜(M)

    • ๋‘˜์งธ์ค„: 1~N๋ฒˆ๊นŒ์ง€์˜ ํฌ์ผ“๋ชฌ ํ•œ ์ค„์”ฉ

    • ์…‹์งธ์ค„: ๋งž์ถฐ์•ผ ํ•˜๋Š” ๋ฌธ์ œ M๊ฐœ ํ•œ ์ค„์”ฉ

    • ํฌ์ผ“๋ชฌ ์ด๋ฆ„ ์ตœ๋Œ€ ๊ธธ์ด: 20

  • ์ถœ๋ ฅ

    • ๋ฌธ์ œ๊ฐ€ ์•ŒํŒŒ๋ฒณ -> ํฌ์ผ“๋ชฌ ๋ฒˆํ˜ธ๋กœ ์‘๋‹ต

    • ๋ฌธ์ œ๊ฐ€ ํฌ์ผ“๋ชฌ ๋ฒˆํ˜ธ -> ํฌ์ผ“๋ชฌ ๋ฒˆํ˜ธ์— ํ•ด๋‹นํ•˜๋Š” ๋ฌธ์ž๋กœ ์‘๋‹ต

    • M๊ฐœ์˜ ์ค„์— ์ฐจ๋ก€๋กœ ๋ฌธ์ œ์— ๋Œ€ํ•œ ๋‹ต์„ ์ถœ๋ ฅ

 

 

๐Ÿ’ป C++ ์ œ์ถœ์ฝ”๋“œ


#include <bits/stdc++.h>

using namespace std;

int main()
{
    int N, M; //N: ํฌ์ผ“๋ชฌ ๊ฐœ์ˆ˜, M: ๋งž์ถฐ์•ผ ํ•˜๋Š” ๋ฌธ์ œ ๊ฐœ์ˆ˜


    scanf("%d %d", &N, &M);

    map<string, int> poketmon1;
    map<int, string> poketmon2;
    vector<string> result;

    for(int i=1; i<=N; i++){
        char input[21]; //ํฌ์ผ“๋ชฌ ์ด๋ฆ„ ์ตœ๋Œ€ ๊ธธ์ด 20
        scanf("%s", &input);

        poketmon1.insert({input, i});
        poketmon2.insert({i, input});
    }

    for(int i=0; i < M; i++){
        char s[21]; //ํฌ์ผ“๋ชฌ ์ด๋ฆ„ ์ตœ๋Œ€ ๊ธธ์ด 20

        scanf("%s", &s); 

        if(atoi(s) != 0){ // if integer, char * -> int         
            string result = poketmon2.at(atoi(s));
            char *a = &*result.begin();
            printf("%s\n", a);
        }
        else{ //if string
            string str1(s);
            const char *a = to_string(poketmon1[str1]).c_str();
            printf("%s\n", a);           
        }     
    } 
}

 

 

๐Ÿ“ ๋ฌธ์ œํ’€์ด ๊ณผ์ •


  • cout์ด๋‚˜ cin์€ ์‹œ๊ฐ„์ด ์˜ค๋ž˜๊ฑธ๋ ค ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•ด์„œ, ์ด cout๊ณผ cin์€ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๊ตฌํ˜„ํ–ˆ๋‹ค.

  • atoi(s) == 0์ด๋ฉด ๋ฌธ์ž์—ด์ด๊ณ , ์•„๋‹ˆ๋ฉด ์ˆซ์ž์ธ ๊ฒƒ์œผ๋กœ ๋ฌธ์ž์—ด, ์ˆซ์ž๋ฅผ ํŒ๋ณ„ํ–ˆ๋‹ค.

  • ์ˆซ์ž๊ฐ€ ๋“ค์–ด์˜ค๋ฉด atoi(s)์ธ key๋กœ poketmon2 ๋งต์—์„œ ์ฐพ๊ณ , char *์œผ๋กœ ๋ณ€ํ™˜ํ•ด์„œ scanf๋กœ ์ถœ๋ ฅํ–ˆ๋‹ค.

  • ๋ฌธ์ž์—ด์ด ๋“ค์–ด์˜ค๋ฉด ๋ฌธ์ž์—ด ๊ทธ๋Œ€๋กœ key๋กœ value๋ฅผ ๊ฐ€์ ธ์™€์„œ int๋ฅผ to_string()์œผ๋กœ string ํ˜•์œผ๋กœ ๋ณ€ํ™˜ ํ›„, c.str()์œผ๋กœ string์„ char * ํ˜•์œผ๋กœ ๋ณ€ํ™˜ํ•ด์„œ ์ถœ๋ ฅํ–ˆ๋‹ค.

  • ํฌ์ผ“๋ชฌ ์ด๋ฆ„์˜ ์ตœ๋Œ€๊ธธ์ด๊ฐ€ 20์ด๋ฏ€๋กœ, null ํฌํ•จ 21 ๊ธธ์ด์˜ ๋ฌธ์ž ๋ฐฐ์—ด์— ์ž…๋ ฅ ๋ฐ›์•˜๋‹ค.

 

 

 

๐Ÿ‘ ๊ฒฐ๊ณผ


  • ์ˆซ์ž์™€ ๋ฌธ์ž์—ด๋กœ ์ž…๋ ฅ์ด ๋“ค์–ด์˜ฌ ๋•Œ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•œ string, int, char * ๊ฐ„์˜ ๋ณ€ํ™˜์— ๋Œ€ํ•ด ์ƒ๊ฐํ•ด๋ณผ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ