포스트

1620번

백준 문제풀이

1620번

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
	int num;
	char name[21];
}Pokemon;

int cmp1(const void* a, const void* b) {
	return strcmp(((Pokemon*)a)->name, ((Pokemon*)b)->name);
}
int cmp2(const void* a, const void* b) {
	return ((Pokemon*)a)->num - ((Pokemon*)b)->num;
}
int main() {
	int n, m;
	scanf("%d %d", &n, &m);

	Pokemon* pokemon = (Pokemon*)malloc(sizeof(Pokemon) * n);
	Pokemon* pokemon2 = (Pokemon*)malloc(sizeof(Pokemon) * n);
	for (int i = 0;i < n;i++) {
		scanf("%s", pokemon[i].name);
		pokemon[i].num = i + 1;

		strcpy(pokemon2[i].name, pokemon[i].name);
		pokemon2[i].num = pokemon[i].num;
	}

	qsort(pokemon, n, sizeof(Pokemon), cmp1);
	//qsort(pokemon2, n, sizeof(Pokemon), cmp2);

	for (int i = 0;i < m;i++) {
		char quiz[21];
		scanf("%s", quiz);

		if (quiz[0] >= '0' && quiz[0] <= '9') {
			
			int a = atoi(quiz);
			printf("%s\n", pokemon2[a-1].name);

			/*
			int start = 0;
			int end = n - 1;
			while (start <= end) {
				int mid = (start + end) / 2;
				int cmp;
				if (pokemon2[mid].num == a) cmp = 0;
				else if (pokemon2[mid].num < a) cmp = 1;
				else if(pokemon2[mid].num > a) cmp = -1;

				//printf("	%s\n", pokemon[mid].name);

				if (cmp == 0) {

					printf("%s\n", pokemon2[mid].name);
					break;
				}
				else if (cmp > 0) start = mid + 1;
				else end = mid - 1;
			}

			*/

		}
		else {
			
			int start = 0;
			int end = n - 1;
			while (start <= end) {
				int mid = (start + end) / 2;	
				int cmp = strcmp(pokemon[mid].name, quiz);
				//printf("	%s\n", pokemon[mid].name);


				if (cmp == 0) {
					
					printf("%d\n", pokemon[mid].num);
					break;
				}
				else if (cmp < 0) start = mid + 1;
				else end = mid - 1;
			}

			/*
			for (int j = 0;j < n;j++) {


				if (strcmp(pokemon[j].name, quiz) == 0) {
					printf("%d\n", pokemon[j].num);
					break;
				}
			}
			*/
		}
	}

	free(pokemon);
	free(pokemon2);
}