hades

[Baekjoon] 1620๋ฒˆ: ๋‚˜๋Š”์•ผ ํฌ์ผ“๋ชฌ ๋งˆ์Šคํ„ฐ ์ด๋‹ค์†œ ๋ณธ๋ฌธ

๐Ÿ‘Š PS/Algorithm

[Baekjoon] 1620๋ฒˆ: ๋‚˜๋Š”์•ผ ํฌ์ผ“๋ชฌ ๋งˆ์Šคํ„ฐ ์ด๋‹ค์†œ

hades1 2024. 7. 7. 16:10

๐Ÿฅ… ๋ฌธ์ œ

https://www.acmicpc.net/problem/1620

 

๐Ÿ” ์„ค๊ณ„

ํฌ์ผ“๋ชฌ๋“ค์˜ ์ด๋ฆ„์ด ์ฃผ์–ด์ง€๊ณ , ์ž…๋ ฅ์ด ํฌ์ผ“๋ชฌ์˜ ์ด๋ฆ„์ด๋ฉด ๋ฒˆํ˜ธ๋ฅผ, ๋ฒˆํ˜ธ์ด๋ฉด ํฌ์ผ“๋ชฌ์˜ ์ด๋ฆ„์„ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค. C++์—์„œ string๊ณผ int๋ฅผ ์—ฐ๊ด€์ง€์œผ๋ฉด์„œ๋„ ์†๋„๊ฐ€ ๋น ๋ฅธ ์ž๋ฃŒ๊ตฌ์กฐ์—๋Š” ํŠธ๋ฆฌ ๊ธฐ๋ฐ˜์ธ map์ด ์žˆ๋‹ค. map์„ ํ™œ์šฉํ•˜์—ฌ ํฌ์ผ“๋ชฌ ๋„๊ฐ์„ ๋งŒ๋“ ๋‹ค. 

 

key:value๊ฐ€ ์ด๋ฆ„:๋ฒˆํ˜ธ, ๋ฒˆํ˜ธ:์ด๋ฆ„์ธ ๋„๊ฐ์„ ๋‘ ๊ฐœ ๋งŒ๋“ค์–ด์„œ ํ•ด๊ฒฐํ–ˆ๋‹ค. map ํด๋ž˜์Šค์—์„œ find ํ•จ์ˆ˜๋Š” map ์•ˆ์— ์ „๋‹ฌํ•˜๋Š” key ๊ฐ’์ด ์—†๋‹ค๋ฉด, map.end()๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. 

 

๐Ÿ‘Š ํ’€์ด

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
using namespace std;	
int n, m;
string name, target;
map<string, int> dogam1;
map<int, string> dogam2;

int main() {
	cin.tie(NULL);
	ios_base::sync_with_stdio(false);
	cin >> n >> m;
	for (int i=1; i<=n; i++){
		cin >> name;
		dogam1.insert({name, i});
		dogam2.insert({i, name});
	}
	for (int i=1; i<=m; i++){
		cin >> target;
		if (dogam1.find(target) == dogam1.end()) {
			cout << dogam2.find(stoi(target))->second << "\n";
		}
		else{
			cout << dogam1.find(target)->second << "\n";
		}
	}
	
	return 0;
}

 

๋„๊ฐ์„ ๋‘ ๊ฐœ๋กœ ๋‚˜๋ˆ„์–ด์„œ ํ•ด๊ฒฐํ–ˆ์ง€๋งŒ, ๋ฒˆํ˜ธ๋„ string ์ทจ๊ธ‰ํ•˜์—ฌ ํ•˜๋‚˜์˜ ๋„๊ฐ์—์„œ ํ•ด๊ฒฐํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ๋‹ค.

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int n, m;
string s;
map<string, string> dogam;

int main(void){
    ios::sync_with_stdio(false);
	cin.tie(NULL);
    cin >> n >> m;
    for (int i=1;i<=n;i++){
        cin >> s;
        dogam[s] = to_string(i);
        dogam[to_string(i)] = s;
    }
    for (int i=0; i<m; i++){
        cin >> s;
        cout << dogam[s] << "\n";
    }
    
    return 0;
}