[ ALGORITHM ]/[ 백 준 ]

[BAEKJOON] 10816번 : 숫자 카드 2

HiStar__ 2020. 8. 12. 13:28

문 제

 

소 스  코 드

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

int main() {
	std::ios_base::sync_with_stdio(false);
	std::cin.tie(NULL);
	std::cout.tie(NULL);

	int N;
	std::cin >> N;

	std::vector<int> cards;

	cards.reserve(N);
	
	int num;
	for (int i = 0; i < N; ++i) {
		std::cin >> num;
		cards.emplace_back(num);
	}

	std::sort(cards.begin(), cards.end());

	int ans_count, ans;
	std::cin >> ans_count;
	for (int i = 0; i < ans_count; ++i) {
		std::cin >> ans;
		
		auto low = std::lower_bound(cards.begin(), cards.end(), ans);
		auto end = std::upper_bound(cards.begin(), cards.end(), ans);
		std::cout << end - low << '\n';
	}

	return 0;
}

 

풀 이

 

  • STL vector를 통하여 입력을 받은 후, lower_bound, upper_bound 함수를 통하여 값의 시작 지점과 끝 지점을 
    뺄 경우 그 카드의 갯수가 나온다.

#include <iostream>
#include <map>

int main() {
	std::ios_base::sync_with_stdio(false);
	std::cin.tie(NULL);
	std::cout.tie(NULL);
	
	int N;
	std::cin >> N;

	std::map<int, int> cards;

	int num;
	for (int i = 0; i < N; ++i) {
		std::cin >> num;
		++cards[num];
	}

	std::cin >> N;
	for (int i = 0; i < N; ++i) {
		std::cin >> num;
		std::cout << cards[num] << '\n';
	}

	return 0;
}

 

STL map 컨테이너를 사용하여 입력과 동시에 정렬과 갯수를 추가해 주는 것은 vector를 사용한 코드 보다 오래 걸린다.

 

출 력 값

 

 

문 제  출 처

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

 

10816번: 숫자 카드 2

첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,

www.acmicpc.net