Dolphins의 HelloWorld

[백준]Baekjoon11652(정렬)(map 활용) 본문

Algorithm/baekjoon문제풀이

[백준]Baekjoon11652(정렬)(map 활용)

돌핀's 2018. 8. 12. 15:55

문제링크 : https://www.acmicpc.net/problem/11652





처음에 이 문제를 봤을 때는 받는 숫자와 그 수가 나온 횟수를 함께 저장한 후 


계속 검사를 하면서 만약 새로운 수가 들어왔을 때 


vector안에 그 숫자가 이미 있는지를 확인하고 만약 있다면 횟수를 늘리고


없다면 새로 vector안에 추가시켜주는 식으로 코드를 짜 보았다.


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Card {
	long long number;
	long long count;
};
bool cmp(const Card &a, const Card &b) {
	if (a.count > b.count) return true;
	else if (a.count == b.count)
		return a.number < b.number;
	else
		return false;
}
int main()
{
	long long n;
	scanf("%lld", &n);
	long long x;
	vector<Card> v;

	while (n--) {
		bool b = true;
		scanf("%lld", &x);
		for (int i = 0; i < v.size(); i++) {
			if (v[i].number == x) {
				v[i].count++;
				b = false; break;
			}
		}
		if (b) {
			Card c;
			c.number = x; c.count = 0;
			v.push_back(c);
		}
	}
	sort(v.begin(), v.end(), cmp);
	printf("%lld\n", v[0].number);
}


이런식으로 해 보았더니 문제 자체는 맞긴 했지만 비효율적이라는 생각이 들었고


map을 사용한다면 훨씬 쉽게 코드를 짤 수 있겠다는 생각이 들었다.


map은 애초에 key와 value로 이루어져있기 때문에 넣는 숫자가 이미 존재하는지


따로 검사해줄 필요가 없다는 것이 장점이다.


아래는 map을 통해 다시 작성한 풀이이다.


#include <iostream>
#include <algorithm>
#include <map>

using namespace std;

int main()
{
	long long N, num;
	map<long long, int> m;
	scanf("%lld", &N);
	while (N--) {
		scanf("%lld", &num);
		m[num]++;
	}
	int max = 0;
	long long result;
	for(auto n:m)
		if (n.second > max) {
			max = n.second;
			result = n.first;
		}
	printf("%lld\n", result);
}


'Algorithm > baekjoon문제풀이' 카테고리의 다른 글

[백준]Baekjoon1377(정렬)  (0) 2018.08.14
[백준]Baekjoon11004(정렬)  (0) 2018.08.12
[백준]Baekjoon10989(정렬)  (0) 2018.08.12
[백준]Baekjoon10814(정렬)  (0) 2018.08.12
[백준]Baekjoon2751(정렬)  (0) 2018.08.11
Comments