본문 바로가기
코딩테스트_백준풀이

배 #1092 c++ 풀이

by wanna_dev 2023. 11. 24.

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

 

1092번: 배

첫째 줄에 N이 주어진다. N은 50보다 작거나 같은 자연수이다. 둘째 줄에는 각 크레인의 무게 제한이 주어진다. 이 값은 1,000,000보다 작거나 같다. 셋째 줄에는 박스의 수 M이 주어진다. M은 10,000보

www.acmicpc.net

시간초과가 난 코드이다. 복잡도가 10^10(10^6 * 10^4)인 코드.

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

using namespace std;

vector<int> v1; // 크레인의 수와 제약
vector<int> v2; // 화물의 무게
//int dp[1000];

bool comp(int a, int b) {
	return a > b;
}
int main() {
	int n, k;
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> n; 



	for (int i = 0; i < n; i++) {
		int temp;
		cin >> temp;
		v1.push_back(temp);

	}
	cin >> k;
	for (int i = 0; i < k; i++) {
		int temp;
		cin >> temp;
		v2.push_back(temp);

	}
	sort(v1.begin(), v1.end());
	sort(v2.begin(), v2.end());
	
	int time = 0; 
	int idx = 0; 
	int size = v1.size();

	while (!v2.empty()) {
		
		for (int i = 0; i < size; i++) {
			int temp;
			temp = v1.back();
			if (v2.back() <= v1[i]) {
				v2.pop_back();				
			}
		}
		time++;
	}

	cout << time;
	
	return 0;
}

 

정답코드는 다음과 같다.

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

using namespace std;

vector<int> v1; // 크레인의 수와 제약
vector<int> v2; // 화물의 무게
//int dp[1000];

bool comp(int a, int b) {
	return a > b;
}
int main() {
	int n, k;
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	cin >> n; 



	for (int i = 0; i < n; i++) {
		int temp;
		cin >> temp;
		v1.push_back(temp);

	}
	cin >> k;
	for (int i = 0; i < k; i++) {
		int temp;
		cin >> temp;
		v2.push_back(temp);

	}
	sort(v1.begin(), v1.end());
	sort(v2.begin(), v2.end());
	if (v1[v1.size() - 1] < v2[v2.size() - 1]) {
		cout << -1 << endl;
		return 0;

	}
	int time = 0;
	while (!v2.empty()) {
		for (int i = v1.size()-1; i >= 0; i--) {
			if (v2.empty())break;
			if (v1[i] >= v2.back()) {
				v2.pop_back();
			}
			else {
				for (int j = v2.size() - 2; j >= 0; j--) {
					if (v1[i] >= v2[j]) {
						v2.erase(v2.begin() + j);
						break;
					}
				}
			}
		}
		time++;
	}

	cout << time;
	
	return 0;
}

'코딩테스트_백준풀이' 카테고리의 다른 글

BOJ 2493 탑 G5 Java  (1) 2024.02.05
BOJ 1244 스위치 켜고 끄기 JAVA  (0) 2024.01.29
센서 #2212 c++ 풀이  (0) 2023.11.24
강의실 배정 #11000  (1) 2023.11.23
로프 #2217 c++ 풀이  (0) 2023.11.22