๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 1946_์‹ ์ž… ์‚ฌ์›

๋ฟŒ์•ผ._. 2023. 10. 16. 16:11

Silver I

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/1946)

< ์‹ ์ž… ์‚ฌ์› >

 

๋ฌธ์ œ ํ’€์ด 

 

์ฒ˜์Œ์—๋Š” ์ž…๋ ฅ๋ฐ›์€ ์„ฑ์ ์„ ์„œ๋ฅ˜ ์‹ฌ์‚ฌ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ–ˆ๋‹ค. ๊ทธ ํ›„ ๋ฉด์ ‘ ์„ฑ์ ์„ ์ด์ค‘ for๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ ๋‹ค๋ฅธ ๋ชจ๋“  ์‚ฌ๋žŒ๋ณด๋‹ค ์„ฑ์ ์ด ๋–จ์–ด์ง€์ง€ ์•Š๋Š”์ง€ ํ™•์ธํ–ˆ๋‹ค. ์ด๋ ‡๊ฒŒ ํ•  ๊ฒฝ์šฐ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

 

for๋ฌธ์„ ํ•œ ๋ฒˆ ์‚ฌ์šฉํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์ฐพ๋‹ค๊ฐ€ ๋– ์˜ค๋ฅด์ง€ ์•Š์•„ ์ฐพ์•„๋ดค๋‹ค,,

๋จผ์ € ์„œ๋ฅ˜ ์„ฑ์ ์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„ ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค. ๊ทธ ํ›„์— ๋ฉด์ ‘ ์„ฑ์ ์„ ๊ธฐ์ค€์œผ๋กœ ์ตœ์†Ÿ๊ฐ’์„ ์ฐพ๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ•œ๋‹ค.

 

 my solution (Java)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

public class _1946_ { // ์‹ ์ž… ์‚ฌ์›
	static class Person implements Comparable<Person> {
		private int a;
		private int b;

		public Person(int a, int b) {
			this.a = a;
			this.b = b;
		}

		@Override
		public int compareTo(Person o) {
			return this.a - o.a;
		}

	}

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		StringTokenizer st;

		int t = Integer.parseInt(bf.readLine());

		ArrayList<Person> arr = new ArrayList<>();
		for (int i = 0; i < t; i++) {
			int n = Integer.parseInt(bf.readLine());

			for (int j = 0; j < n; j++) {
				st = new StringTokenizer(bf.readLine());
				arr.add(new Person(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())));
			}

			Collections.sort(arr);

			int result = 1;
			int idx = 0;
			for (int j = 1; j < n; j++) {
				if (arr.get(idx).b > arr.get(j).b) {
					result += 1;
					idx = j;
				}
			}
			bw.write(result + "\n");
			arr.clear();
		}
		bw.flush();
	}
}

 

Main

๋ณ€์ˆ˜)
t : ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ๊ฐœ์ˆ˜
arr : ์‹ ์ž…์‚ฌ์› ์„ฑ์  ์ €์žฅ 
n : ์ง€์›์ž์˜ ์ˆซ์ž
result : ์„ ๋ฐœํ•  ์ˆ˜ ์žˆ๋Š” ์‹ ์ž…์‚ฌ์› ์ˆ˜
idx : index

 

- ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ๊ฐœ์ˆ˜(t) ์ž…๋ ฅ

- ์ง€์›์ž์˜ ์ˆซ์ž(n) ์ž…๋ ฅ

- ์ง€์›์ž์˜ ์„ฑ์ ์„ ์ž…๋ ฅ๋ฐ›์•„ arr์— ์ €์žฅ

- ์„œ๋ฅ˜ ์‹ฌ์‚ฌ ์„ฑ์ ์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ

- arr ์ˆœํ™˜

: ๋ฉด์ ‘ ์„ฑ์ ์ด ์ˆœํ™˜ํ•˜๋Š” ์‚ฌ๋žŒ์˜ ๋ฉด์ ‘ ์„ฑ์ ๋ณด๋‹ค ๋“ฑ์ˆ˜๊ฐ€ ํฌ๋‹ค๋ฉด ์„ ๋ฐœํ•  ์ˆ˜ ์žˆ๋Š” ์‹ ์ž…์‚ฌ์› ์ˆ˜ ์ฆ๊ฐ€ ๋ฐ idx๋ฅผ ๊ทธ ๊ฐ’์œผ๋กœ ๊ต์ฒด

(์„œ๋ฅ˜ ์„ฑ์ ์„ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ–ˆ๋‹ค๋ฉด ๋ฉด์ ‘ ์„ฑ์ ์ด ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋ ์ˆ˜๋ก ์„ ๋ฐœํ•  ์ˆ˜ ์žˆ๋Š” ์‹ ์ž…์‚ฌ์›์˜ ์ˆ˜๊ฐ€ ๋Š˜์–ด๋‚จ)