홍시홍의 프로그래밍

[백준 1620] 나는야 포켓몬 마스터 본문

알고리즘 문제풀이/백준

[백준 1620] 나는야 포켓몬 마스터

홍시홍 2020. 3. 2. 23:13

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

 

1620번: 나는야 포켓몬 마스터 이다솜

첫째 줄에는 도감에 수록되어 있는 포켓몬의 개수 N이랑 내가 맞춰야 하는 문제의 개수 M이 주어져. N과 M은 1보다 크거나 같고, 100,000보다 작거나 같은 자연수인데, 자연수가 뭔지는 알지? 모르면 물어봐도 괜찮아. 나는 언제든지 질문에 답해줄 준비가 되어있어. 둘째 줄부터 N개의 줄에 포켓몬의 번호가 1번인 포켓몬부터 N번에 해당하는 포켓몬까지 한 줄에 하나씩 입력으로 들어와. 포켓몬의 이름은 모두 영어로만 이루어져있고, 또, 음... 첫 글자만

www.acmicpc.net

요구사항

문자열이 입력되어질때, 해당 index출력하기

index일때는 문자열 출력하기

 

풀이

1. index일때는 입력받을때 순서대로 받아서 해당 index출력

2. 문자일 경우는 HASH로 구현

 

#include <iostream>
#include <queue>
#include <math.h>
#include <algorithm>
#include <functional>
#include <string>
#include <string.h>
using namespace std;
const int MAX = 123731;
const int PN = 23;
struct go {
	int key_num;
	char key_name[20];
};
char hash_raw[MAX][25];
int n, m;
int table[MAX][50];
int keysave[MAX];
int hash_size = 0;
unsigned int get_key(char str[]) {
	unsigned int key = 0, p = 1;
	for (int i = 0; str[i] != 0; i++) {
		key = +(str[i] * p);
		p *= PN;
	}
	return key%MAX;
}
int my_strcmp(char a[], char b[]) {
	int i = 0, j = 0;
	while (a[i]) {
		if (a[i++] != b[j++]) {
			i--, j--;
			break;
		}
	}
	return a[i] - b[j];
}
int contain(char str[]) {
	unsigned int key = get_key(str);
	int size = table[key][0];
	for (int i = 1; i <= size; i++) {
		int pos = table[key][i];
		if (my_strcmp(hash_raw[pos], str) == 0) {
			return pos;
		}
	}
	return -1;
}
void add(char str[],int value) {
	unsigned int key = get_key(str);
	int i = 0;
	for(i=0; str[i]!=0 ;i++){
		hash_raw[hash_size][i] = str[i];
	}
	hash_raw[hash_size][i] =0;

	int &size = table[key][0];
	keysave[hash_size] = value;
	table[key][++size] = hash_size++;
}
int main() {
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++) {
		char ch[25];
		scanf("%s", &ch);
		add(ch,i);
	}
	for (int i = 0; i < m; i++) {
		char ch[25];
		scanf("%s", &ch);
		//cout << i << endl;
		if (ch[0] == '0'||ch[0] == '1' || ch[0] == '2' || ch[0] == '3' || ch[0] == '4' || ch[0] == '5' || ch[0] == '6' || ch[0] == '7' || ch[0] == '8' || ch[0] == '9')
		{
			int x = stoi(ch)-1;
			printf("%s\n", hash_raw[x]);
		}
		else {
			printf("%d\n", keysave[contain(ch)]);
		}
	}
}

'알고리즘 문제풀이 > 백준' 카테고리의 다른 글

[백준 2983] 개구리 공주  (0) 2020.03.04
[백준 6118] 숨바꼭질  (0) 2020.03.04
[백준 10774] 저지  (0) 2020.03.02
[백준 4343] Arctic Network  (0) 2020.03.02
[백준 1377] 버블 소트  (0) 2020.02.29
Comments