매일 Algorithm

신재원·2023년 3월 23일
0

Algorithm

목록 보기
74/243

백준 9372번 (그래프 이론)

import java.util.Scanner;

public class problem231 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int test =in.nextInt();
        StringBuilder sb = new StringBuilder();
        // 트리의 간선 노드 - 1
        for(int i = 0; i < test; i++){
            int n = in.nextInt(); // 국가의 갯수
            int m = in.nextInt(); // 비행기 종류

            for(int j = 0; j < m; j++){
                int a = in.nextInt();
                int b = in.nextInt();
            }
            sb.append(n -1).append("\n");
        }

        System.out.print(sb.toString());


    }
}

프로그래머스 LEVEL 1 복습

import java.util.*;
class Solution {
    public int[] solution(int[] numbers) {
        Set <Integer> set = new HashSet<>();
        
        
        for(int i = 0; i < numbers.length; i++){
            for(int j = i + 1; j < numbers.length; j++){
                int sum = numbers[i]+ numbers[j];
                set.add(sum);
            }
        }
      // 중복이 제거된 Set 컬렉션을 담아준다. 값을 List에서 꺼내준다.
        List<Integer> list = new ArrayList<>(set);
        int [] answer = new int[list.size()];
        for(int i = 0; i < list.size(); i++){
            answer[i] = list.get(i);
        }
        Arrays.sort(answer);
        return answer;
    }
}
프로그래머스 : 크기가 작은 부분문자열
class Solution {
    public int solution(String t, String p) {
        int answer = 0;
        
        // p의 길이만큼 잘라서 비교함으로 조건을 작성해준다.
        for(int i = 0; i < t.length() - p.length() + 1; i++){
            // Long타입으로 타입변환
            Long s = Long.parseLong(t.substring(i,p.length()+i));
            if(Long.parseLong(p) >= s){
                answer++;
            }
        }
        return answer;
    }
}
프로그래머스 : 콜라문제 
class Solution {
    public int solution(int a, int b, int n) {
        int answer = 0;
        
        while(true){
            if(a > n){
                break;
            }
            answer += (n/a) * b;
            // 빈 병 재고
            int stock = n % a;
            n = (n/a) * b + stock;
        }
        return answer;
    }
}

백준 15903번 (그리디)

import java.util.Arrays;
import java.util.Scanner;

public class problem232 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int size = in.nextInt();
        int a = in.nextInt();
        long[] arr = new long[size];

        for (int i = 0; i < size; i++) {
            arr[i] = in.nextInt();
        }


        for (int i = 0; i < a; i++) {
            Arrays.sort(arr); // 배열을 계속 오름차순
            // arr[0], arr[1] 값을 바인딩
            long sum = arr[0] + arr[1];
            arr[0] = sum;
            arr[1] = sum;

        }

        long result = 0;
        for (int i = 0; i < size; i++) {
            result += arr[i];
        }
        System.out.print(result);

    }
}

0개의 댓글