알고리즘

[boj11728/c++] 배열 합치기

IT 참다랑어 2023. 5. 4. 00:18

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

 

11728번: 배열 합치기

첫째 줄에 배열 A의 크기 N, 배열 B의 크기 M이 주어진다. (1 ≤ N, M ≤ 1,000,000) 둘째 줄에는 배열 A의 내용이, 셋째 줄에는 배열 B의 내용이 주어진다. 배열에 들어있는 수는 절댓값이 109보다 작거

www.acmicpc.net

투포인터 이용해서 해결할 수 있는 문제

priority queue를 활용하면 메모리는 더 적게 걸리면서 해결할 수 있음. 하지만 시간이 더 오래..

아 total 안만들고 그냥 바로 출력해도 되는데 어쨌든 두 배열중에 하나는 빨리 끝나니까 while문으로 배열 끝까지 탐색할 수 있도록 해주기!

 

#include <iostream>
#include <vector>

using namespace std;
int N, M;
vector<int> arr1;
vector<int> arr2;
vector<int> total;
int nidx, midx;

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> N >> M;
	int temp;
	for (int i = 0; i < N; i++) {
		cin >> temp;
		arr1.push_back(temp);
	}
	for (int i = 0; i < M; i++) {
		cin >> temp;
		arr2.push_back(temp);
	}

	while (nidx < N && midx < M) {
		if (arr1[nidx] <= arr2[midx]) {
			total.push_back(arr1[nidx++]);
		}
		else {
			total.push_back(arr2[midx++]);
		}
	}
	if (nidx < N) {
		while (nidx != N) {
			total.push_back(arr1[nidx++]);
		}
	}
	if (midx < M) {
		while (midx != M) {
			total.push_back(arr2[midx++]);
		}
	}

	for (int i = 0; i < total.size(); i++) {
		cout << total[i] << ' ';
	}
}