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

[Codeforces] 1005A: Tanya and Stairways

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

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

 

Problem - 1005A - Codeforces

 

codeforces.com

์ฝ”๋“œ

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Main { 

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(bf.readLine());
		StringTokenizer st = new StringTokenizer(bf.readLine());
		int[] arr = new int[n];
		for(int i=0; i<arr.length; i++)
			arr[i] = Integer.parseInt(st.nextToken());
		
		int stairways = 1;	// ๊ณ„๋‹จ ์ˆ˜
		List<Integer> list = new ArrayList<Integer>();	// ๊ฐ ๊ณ„๋‹จ์— ํฌํ•จ๋œ ๊ณ„๋‹จ์ˆ˜
		for(int i=0; i<arr.length-1; i++) {
			if(arr[i] >= arr[i+1]) {	// ๊ณ„๋‹จ ์ˆ˜๊ฐ€ ๊ฐ์†Œํ•˜๋Š” ๋ถ€๋ถ„ -> ๊ณ„๋‹จ ์ˆ˜ ์ฆ๊ฐ€
				stairways ++;
				list.add(arr[i]);
			}
		}
		list.add(arr[arr.length-1]);	// ๋งˆ์ง€๋ง‰ ๊ณ„๋‹จ์€ ๋ฌด์กฐ๊ฑด ํฌํ•จ
		
		System.out.println(stairways);
		for(int i : list)
			System.out.print(i + " ");
		
		bf.close();
	}

}

ํ’€์ด

์ฃผ์–ด์ง„ ์˜ˆ์ œ์—์„œ ๊ณ„๋‹จ์ˆ˜์™€, ๊ฐ ๊ณ„๋‹จ์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ๋‹ค.

์œ„์—์„  [1, 2, 3]์˜ ์„ธ ๊ฐœ์งœ๋ฆฌ ๊ณ„๋‹จ๊ณผ [1, 2, 3, 4]์˜ ๋„ค ๊ฐœ์งœ๋ฆฌ ๊ณ„๋‹จ ๋‘๊ฐœ๊ฐ€ ์žˆ๋‹ค.

๋”ฐ๋ผ์„œ ์ด 2๊ฐœ์˜ ๊ณ„๋‹จ๊ณผ 3์นธ, 4์นธ ๊ณ„๋‹จ์„ ์ถœ๋ ฅํ•œ๋‹ค.

 

๋จผ์ € ์ž…๋ ฅ์„ ๋ฐ›๊ณ , ๋ฐฐ์—ด์— ์ €์žฅํ•œ๋‹ค.

arr= [1, 2, 3, 1, 2, 3, 4]

๊ทธ ํ›„ ๋ฐฐ์—ด์˜ ๊ฐ’ ์ค‘ ์ด์ „ ๊ฐ’๋ณด๋‹ค ์ž‘์•„์ง€๋Š” ๊ฒฝ์šฐ[3, 1]

์ƒˆ๋กœ์šด ๊ณ„๋‹จ์˜ ์‹œ์ž‘์ด๋ฏ€๋กœ ๊ณ„๋‹จ์ˆ˜๋ฅผ ++์‹œ์ผœ์ฃผ๊ณ , ์ž‘์•„์ง€๊ธฐ ์ „์˜ ๊ฐ’[3]์„ ArrayList์— ์ €์žฅํ•œ๋‹ค.

 

์œ„ ๊ณผ์ •์„ ๋ฐฐ์—ด์ด ๋๋‚ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋Š”๋ฐ, ๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰ ๊ฐ’์€ ํ•ญ์ƒ ๊ฐ€์žฅ ํฐ ๊ฐ’์ด๋ฏ€๋กœ ArrayList์— ์ €์žฅํ•œ๋‹ค.

๊ทธ ํ›„ ๊ณ„๋‹จ์ˆ˜์™€ ๊ฐ ๊ณ„๋‹จ์ด ๋ช‡๊ฐœ์งœ๋ฆฌ ๊ณ„๋‹จ์ธ์ง€ ์ถœ๋ ฅํ•˜๋ฉด ๋œ๋‹ค.

 

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€