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

[Codeforces] 1257A: Two Rival Students

by ์ฃผ๋ฐœ2 2020. 3. 18.
๋ฐ˜์‘ํ˜•

https://codeforces.com/problemset/problem/1257/A

 

Problem - 1257A - Codeforces

 

codeforces.com

์ฝ”๋“œ

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		int t = scan.nextInt();
		for(int tc=0; tc<t; tc++) {
			int n = scan.nextInt();	// ํ•™์ƒ ์ˆ˜
			int x = scan.nextInt();	// ์Šค์™‘ ์ˆ˜
			int a = scan.nextInt();	// ํ•™์ƒ 1
			int b = scan.nextInt();	// ํ•™์ƒ 2
			int max = 0;	// ๋‘ ํ•™์ƒ์‚ฌ์ด ์ตœ๋Œ€๊ฑฐ๋ฆฌ
			
			// swap ๊ธฐํšŒ๊ฐ€ 0์ด๋ฉด ๋ฐ”๋กœ ์ถœ๋ ฅ
			if(x == 0) {
				System.out.println(Math.abs(a-b));
				continue;
			}
			
			// swap์„ ํ•˜์ง€ ์•Š์•„๋„ ์ด๋ฏธ ๋‘ํ•™์ƒ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ๋Œ€์ผ๊ฒฝ์šฐ๋„ ์ด๋ฏธ ์ถœ๋ ฅ
			if(Math.abs(a-b) + 1 == n) {
				System.out.println(Math.abs(a-b));
				continue;
			}
			
			// ์œ„ ๋‘๊ฒฝ์šฐ๋ฅผ ์ œ์™ธํ•˜๊ณค ๋‘ํ•™์ƒ ๊ฑฐ๋ฆฌ๋ฅผ swapํšŸ์ˆ˜๋งŒํผ ๋Š˜๋ฆฐ๋‹ค.
			int diff = Math.abs(a-b) + x;
			
			// ๋‘ํ•™์ƒ ๊ฑฐ๋ฆฌ๋ฅผ swapํšŸ์ˆ˜๋งŒํผ ๋Š˜๋ ธ์„๋•Œ, ๊ธฐ์กด์˜ ์ตœ๋Œ€๋ฒ”์œ„๋ฅผ ๋„˜์„๊ฒฝ์šฐ
			if(diff >= n)
				System.out.println(n-1);
			else
				System.out.println(diff);
		}
		
		scan.close();

	}

}

ํ’€์ด

x ์ˆ˜๋งŒํผ ๋‘ ํ•™์ƒ์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๋ฒŒ๋ฆด ์ˆ˜ ์žˆ๊ณ , ๋‘ ํ•™์ƒ์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ๋Œ€๊ฐ€ ๋˜๋„๋ก ๋งŒ๋“ค๊ธฐ.

 

1) ์ฃผ์–ด์ง„ swap์˜ ๊ธฐํšŒ๊ฐ€ 0์ธ๊ฒฝ์šฐ(x = 0) 

 - ๋‘ ํ•™์ƒ์„ ์ด๋™ํ•  ์ˆ˜ ์—†์œผ๋ฏ€๋กœ ํ˜„์žฌ ๋‘ ํ•™์ƒ์˜ ๊ฑฐ๋ฆฌ ์ฐจ์ด๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

2) ์ฃผ์–ด์ง„ swap์˜ ๊ธฐํšŒ์™€ ์ƒ๊ด€์—†์ด ์ด๋ฏธ ๋‘ ํ•™์ƒ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ๊ฐ€ ์ตœ๋Œ€์ผ๋•Œ

 - ๊ทธ๋ƒฅ ํ˜„์žฌ ๋‘ ํ•™์ƒ์˜ ๊ฑฐ๋ฆฌ ์ฐจ์ด๊ฐ€ ์ตœ๋Œ€์ด๋ฏ€๋กœ ๊ทธ๋Œ€๋กœ ์ถœ๋ ฅํ•œ๋‹ค.

 

3) ์œ„ ๋‘๊ฐ€์ง€๊ฐ€ ์•„๋‹Œ๊ฒฝ์šฐ, swap์˜ ๊ธฐํšŒ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•œ๋‹ค.

 - ๋‘ ํ•™์ƒ์˜ ๊ฑฐ๋ฆฌ๋Š” ํ˜„์žฌ ๊ฑฐ๋ฆฌ์˜ ์ฐจ์ด์—์„œ swap์˜ ๊ธฐํšŒ๋ฅผ ๋”ํ•˜๋Š”๊ฒŒ ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ๊ฐ€ ๋œ๋‹ค.

 - swap ํ•œ๋ฒˆ๋‹น ๋‘ํ•™์ƒ์˜ ๊ฑฐ๋ฆฌ๋Š” 1์”ฉ ๋ฒŒ์–ด์ง€๊ธฐ ๋•Œ๋ฌธ.

โ— 3-1) ๋งŒ์•ฝ ์œ„ ๊ณผ์ •์—์„œ swap์„ ๋ชจ๋‘ ๋”ํ–ˆ๋Š”๋ฐ ๋‘ ํ•™์ƒ์˜ ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ๋ณด๋‹ค ์ปค์ง€๋Š” ๊ฒฝ์šฐ

   - ๋” ์ปค์ง€๋ฉด ์ฃผ์–ด์ง„ ํ•™์ƒ์ˆ˜๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.(1~n์ด๋ฏ€๋กœ ๊ฑฐ๋ฆฌ์ตœ๋Œ€๋Š” n-1)

โ— 3-2) ์œ„ ๊ณผ์ •์—์„œ swap์„ ๋ชจ๋‘ ๋”ํ–ˆ์„๋•Œ ์ตœ๋Œ€ ๊ฑฐ๋ฆฌ๋ณด๋‹ค ์ž‘์•„์ง€๋Š” ๊ฒฝ์šฐ๋Š” ๊ทธ๋Œ€๋กœ ์ถœ๋ ฅํ•œ๋‹ค.

 

 

 

ํ•œ์ค„ ํ’€์ด

System.out.println(Math.min(n - 1, Math.abs(a - b) + x));

์œ„ ํ•œ์ค„์ด๋ฉด ๋๋‚œ๋‹ค ....................... ;; wOw

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€