๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜/BOJ

[C++/๋ฐฑ์ค€] 11650, 11651 : ์ขŒํ‘œ ์ •๋ ฌํ•˜๊ธฐ 1, 2

728x90

๋ฌธ์ œ(11650)

2์ฐจ์› ํ‰๋ฉด ์œ„์˜ ์  N๊ฐœ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ขŒํ‘œ๋ฅผ x์ขŒํ‘œ๊ฐ€ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆœ์œผ๋กœ, x์ขŒํ‘œ๊ฐ€ ๊ฐ™์œผ๋ฉด y์ขŒํ‘œ๊ฐ€ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆœ์„œ๋กœ ์ •๋ ฌํ•œ ๋‹ค์Œ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ์ ์˜ ๊ฐœ์ˆ˜ N (1 ≤ N ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” i๋ฒˆ์ ์˜ ์œ„์น˜ xi์™€ yi๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (-100,000 ≤ xi, yi ≤ 100,000) ์ขŒํ‘œ๋Š” ํ•ญ์ƒ ์ •์ˆ˜์ด๊ณ , ์œ„์น˜๊ฐ€ ๊ฐ™์€ ๋‘ ์ ์€ ์—†๋‹ค.

์ถœ๋ ฅ

์ฒซ์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์— ์ ์„ ์ •๋ ฌํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.


11650๋ฒˆ์€ x์ขŒํ‘œ ์šฐ์„ ์œผ๋กœ ์ •๋ ฌ ํ›„ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ.

๊ตฌ์กฐ์ฒด์™€ ๋ฒกํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜์˜€๊ณ , algorithm ํ—ค๋”์˜ sort ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ •๋ ฌํ•˜์˜€๋‹ค.

 

sort(v.begin(), v.end(), compare) -> v์˜ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋๊นŒ์ง€, compare๊ฐ€ true์ผ ๋•Œ ์•ž๋’ค ์ˆœ์„œ ๋ณ€๊ฒฝ

 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Coor {
	int x;
	int y;
};

bool compare(Coor a, Coor b) {
	if (a.x == b.x) return a.y < b.y;
	else return a.x < b.x;
}

int main() {
	int n;
	vector<Coor> v;
	cin >> n;
	for (int i = 0; i < n; ++i) {
		Coor coor;
		cin >> coor.x >> coor.y;
		v.push_back(coor);
	}
	sort(v.begin(), v.end(), compare);
	for (int i = 0; i < n; ++i) {
		cout << v[i].x << " " << v[i].y << "\n";
	}
}

 

11651๋ฒˆ์€ ์œ„ ๋ฌธ์ œ์™€ ๋‹ค๋ฅธ ์กฐ๊ฑด์€ ๋ชจ๋‘ ๋™์ผํ•˜๊ณ , y์ขŒํ‘œ ์šฐ์„ ์œผ๋กœ ์ •๋ ฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

๋‘ ์ •์ˆ˜์˜ ํฌ๊ธฐ๋ฅผ ๋น„๊ตํ•˜์—ฌ true/false๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” compare ํ•จ์ˆ˜๋งŒ ์ˆ˜์ •ํ•˜๋ฉด ๋œ๋‹ค.

bool compare(Coor a, Coor b) {
	if (a.y == b.y) return a.x < b.x;
	else return a.y < b.y;
}
728x90