Jun's Development Journey

[BOJ] 6159 코스튬 파티 본문

BOJ/Two Pointer

[BOJ] 6159 코스튬 파티

J_Jayce 2021. 2. 23. 14:24

문제

www.acmicpc.net/problem/6159

 

6159번: 코스튬 파티

한 농부가 할로윈 파티에 그의 소들을 데려가려고한다. 아쉽게도 농부에게는 코스튬이 한벌밖에 없다. 그 코스튬에는 정확하게 사이즈는 S(1 <= S <= 1,000,000)이며, 최대 소 두마리가 들어간다. 농

www.acmicpc.net

풀이

1) 시간 복잡도 비효율적 코드(이중 For문)

import java.io.*;
import java.util.*;

public class Main {
	static int max = -1;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N,S,size[], cnt=0;
        boolean[] chk;
        //입력
        StringTokenizer st = new StringTokenizer(br.readLine()," ");
        N = Integer.parseInt(st.nextToken());
        S = Integer.parseInt(st.nextToken());
        size = new int[N];
        
        for(int i=0;i<N;i++)
        	size[i] = Integer.parseInt(br.readLine());
        
        
        //계산
        for(int i=0;i<N;i++) {
        	for(int j=0;j<N;j++) {
        		if(i!=j && size[i]+size[j]<=S) {
        			cnt++;
        		}
        	}
        }
        System.out.println(cnt/2);
    }
} 

 

2) 효율적인 코드(Two Pointer)

import java.io.*;
import java.util.*;

public class Main {
   
	public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        //선언 및 입력
        int N,S,cows[],cnt=0;
        int end=0;
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        S = Integer.parseInt(st.nextToken());
        cows = new int[N];
        
        for(int i=0;i<N;i++)
        	cows[i] = Integer.parseInt(br.readLine());
        
        //계산
        Arrays.sort(cows);
        for(int start = 0;start<N-1;start++) {
        	end = start+1;
        	if(cows[start]>=S)
        		break;
        	while(end <N && cows[start]+cows[end]<=S) {
        		cnt++;
        		end++;
        	}
        }
        
        System.out.println(cnt);
    }
} 

'BOJ > Two Pointer' 카테고리의 다른 글

[BOJ] 2470번 두 용액  (0) 2021.04.21
[BOJ] 17609 회문  (0) 2021.03.03
[BOJ] 2531 회전초밥  (0) 2021.02.22