Development Palette

[D3] n9229 한빈이와 Spot Mart; 본문

Algorithm/SWEA

[D3] n9229 한빈이와 Spot Mart;

징주 2021. 8. 10. 00:16

package com.swea.w0809.n9229_한빈이와SpotMart;

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


//한빈이가 들고 갈 수 있는 과자 봉지(2개)의 무게 합 최대를 출력하라. --> 조합
//만약 한빈이가 두 과자를 들고 갈 방법이 없는 경우에는 -1을출력한다.
public class Solution {
	static int max;
	final static int CNT = 2;

	public static void combination(int toSelect, int [] selected, int startIdx, int [] snack,int M) {
		int i=0;
		if(toSelect == CNT) {
			int sum = selected[0]+selected[1];
			 if(max < sum & sum<=M)  {
				 max = sum;
			 }
			 else if(startIdx >= snack.length  & max == -99) max = -1;
			
			return;
		}
		
		for(i=startIdx; i<snack.length;i++) {
			selected[toSelect] = snack[i];
			combination(toSelect+1, selected, i+1, snack,M);
		}
	}
	

	public static void main(String[] args) throws  NumberFormatException, IOException {
		System.setIn(new FileInputStream("src\\com\\ssafy\\algo\\n9229한빈이와SpotMart\\sample_input (1).txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int T = Integer.parseInt(br.readLine());
		
		for(int t=1; t<=T; t++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			
			//(2 ≤ N ≤ 1000 , 2 ≤ M ≤ 2000000)
			int N = Integer.parseInt(st.nextToken());		//과자 봉지 수
			int M = Integer.parseInt(st.nextToken());		//N개의 과자의 총 봉지 무게
			
			//N개의 과자 봉지 무게
			int snack [] = new int[N];
			st = new StringTokenizer(br.readLine());		//각 과자봉지의 무게. (1 ≤ ai ≤ 1000000)
			for(int n =0; n<N; n++) {
				snack[n] = Integer.parseInt(st.nextToken());
			}
			
			//N개중에 2개 뽑기
			max = -99;
			combination(0, new int[CNT], 0, snack, M);
			bw.append("#"+ t +" " + max+"\n");
			bw.flush();
		}
		bw.close();
	}

}

https://swexpertacademy.com/main/talk/solvingClub/problemView.do?contestProbId=AW8Wj7cqbY0DFAXN&solveclubId=AXqjxFI6_SQDFATi&problemBoxTitle=08%EC%9B%9409%EC%9D%BC&problemBoxCnt=3&probBoxId=AXsoO1xqw8gDFARW 

 

'Algorithm > SWEA' 카테고리의 다른 글

[D4] n1223_계산기2  (0) 2021.08.20
[D3] n6808_규영이와인영이의카드게임  (0) 2021.08.14
[D3] n3499_퍼펙트셔플  (0) 2021.08.06
[D4] n1218_괄호짝짓기  (0) 2021.08.05
[D3] n1225_암호생성기  (0) 2021.08.05
Comments