728x90

https://www.acmicpc.net/problem/14889

 

14889번: 스타트와 링크

예제 2의 경우에 (1, 3, 6), (2, 4, 5)로 팀을 나누면 되고, 예제 3의 경우에는 (1, 2, 4, 5), (3, 6, 7, 8)로 팀을 나누면 된다.

www.acmicpc.net

 

 

 

풀이)

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

public class Main_BJ_14889_스타트와링크 {
    static int[][] map;
    static int n, ans = Integer.MAX_VALUE;
    static boolean[] visited;
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        map = new int[n][n];
        visited = new boolean[n];
        for(int i=0; i<n; i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            for(int j=0; j<n; j++){
                map[i][j] = Integer.parseInt(st.nextToken());
            }
        }
        comb(0, 0);
        System.out.println(ans);

    }//main
    private static void comb(int idx, int cnt){
        if(cnt == n/2){
            cal();
            return;
        }

        for(int i=idx; i<n; i++){
            if(visited[i])
                continue;

            visited[i] = true;
            comb(i+1, cnt+1);
            visited[i] = false;
        }

    }//comb
    private static void cal(){
        int start=0;
        int link=0;
        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                if(visited[i] && visited[j])
                    start += map[i][j]+map[j][i];
                else if(!visited[i] && !visited[j])
                    link += map[i][j]+map[j][i];
            }
        }
        start /= 2;
        link /= 2;
        ans = Math.min(ans, Math.abs(start-link));
    }
}

조합으로 경우의 수를 구하고, start와 link에 해당하는 점수를 구해주면 된다.

이때, for문으로 돌릴 경우 이중으로 더해진다는 점을 참고하기!!!

(아니면 for문 내에서 자체적으로 두 번 안 더하게끔 하면 된다. 그걸 이제 보고 생각남..ㅎ)

 

처음에는 무조건 4팀중 반반으로 나눠야 하는줄 알고,,,,,,, 실버2맞나...? 생각보다 더 높아야 하는거 아닌가...? 했는데

그게 아니었고 그냥 내가 잘못 본거였다...ㅠ

문제 똑바로 잘 읽기...ㅎ

728x90

'코테 > 백준' 카테고리의 다른 글

백준 15651 N과 M(3) (JAVA)  (0) 2023.05.31
백준 11729 하노이 탑 이동 순서(JAVA)  (0) 2023.05.29
백준 4963 섬의 개수(JAVA)  (0) 2023.05.21
백준 15649 N과 M(1) (JAVA)  (1) 2023.05.16
백준 1427 소트인사이드(JAVA)  (0) 2023.05.09
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/144854

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

풀이)

SELECT b.book_id, a.author_name, date_format(b.published_date, "%Y-%m-%d") as published_date
from book as b join author as a on a.author_id = b.author_id
where b.category = '경제'
order by b.published_date;

join을 쓰고, 경제 카테고리에 맞게 구분을 해준다.

여기에서, date_format 안 맞으면 틀리니까 주의하기....

728x90
728x90

https://www.acmicpc.net/problem/4963

 

4963번: 섬의 개수

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도

www.acmicpc.net

 

 

풀이)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main_BJ_4963_섬의개수 {
    static boolean[][] visited;
    static int[][] map;
    static int ans;
    static int w, h;
    static int[] dx = {-1, 1, 0, 0, -1, 1, -1, 1};
    static int[] dy = {0, 0, -1, 1, -1, -1, 1, 1};
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        w = Integer.parseInt(st.nextToken());
        h = Integer.parseInt(st.nextToken());

        while(w!=0 && h!=0) {
            map = new int[h][w];
            for (int i = 0; i < h; i++) {
                st = new StringTokenizer(br.readLine());
                for (int j = 0; j < w; j++) {
                    map[i][j] = Integer.parseInt(st.nextToken());
                }
            }
            visited = new boolean[h][w];
            for(int i=0; i<h; i++){
                for(int j=0; j<w; j++){
                    if(!visited[i][j] && map[i][j]==1) {
                        bfs(i, j);
                        ans++;
                    }
                }
            }
            System.out.println(ans);
            ans = 0;

            st = new StringTokenizer(br.readLine());
            w = Integer.parseInt(st.nextToken());
            h = Integer.parseInt(st.nextToken());
        }//while
    }//main
    private static void bfs(int x, int y){
        Queue<int[]> q = new ArrayDeque<>();
        q.add(new int[] {x, y});
        visited[x][y] = true;

        while(!q.isEmpty()){
            int[] cur = q.poll();
            for(int i=0; i<8; i++){
                int nx = cur[0]+dx[i];
                int ny = cur[1]+dy[i];

                if(check(nx, ny) && !visited[nx][ny] && map[nx][ny]==1){
                    q.offer(new int[] {nx, ny});
                    visited[nx][ny] = true;
                }
            }
        }
    }//bfs
    private static boolean check(int x, int y){
        if(x<0 || x>=h || y<0 || y>=w)
            return false;
        return true;
    }
}

bfs로 탐색하기 간단한 문제다!

다만, 상하좌우 및 대각선까지 파악해야하므로 dx, dy가 8개가 된다는 사실을 잊지 말아야 한다.

 

728x90

'코테 > 백준' 카테고리의 다른 글

백준 11729 하노이 탑 이동 순서(JAVA)  (0) 2023.05.29
백준 14889 스타트와 링크(JAVA)  (0) 2023.05.23
백준 15649 N과 M(1) (JAVA)  (1) 2023.05.16
백준 1427 소트인사이드(JAVA)  (0) 2023.05.09
백준 1010 다리 놓기(JAVA)  (0) 2023.05.08
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/131533

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

풀이)

select p.product_code as product_code, sum(o.sales_amount)*price as sales
from product as p join offline_sale as o on p.product_id = o.product_id
group by product_code
order by sales desc, product_code asc;

join문제를 처음 풀어보았는데,,,, 헷갈린당,,,,ㅎㅎ

 

728x90
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/133026

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

풀이)

-- 코드를 입력하세요
SELECT i.ingredient_type as ingredient_type, sum(f.total_order) as total_order
from first_half as f, icecream_info as i
where i.flavor = f.flavor
group by i.ingredient_type
order by total_order;

두 개의 테이블을 이용해서 구하는 간단한 문제!

728x90
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/132202

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

풀이)

-- 코드를 입력하세요
SELECT mcdp_cd as "진료과코드", count(distinct apnt_no) as "5월예약건수"
from appointment
where date_format(apnt_ymd, '%Y-%m') = "2022-05"
group by mcdp_cd
order by count(distinct apnt_no),"진료과코드";

이 문제에서 가장 골머리를 앓았던 부분은 order by 절 때문인 것 같다...

order by를 "5월예약건수", "진료과코드"라고 하면 오답이 나온다...

 

 

select mcdp_cd as 진료과코드, count(*) as 5월예약건수
from appointment 
where date_format(apnt_ymd, '%y-%m') like '22-05'
group by mcdp_cd 
order by 5월예약건수 asc, 진료과코드 asc;

그런데,,, 이렇게 하면 또 답이란다

뭔 차이지?ㅠ

728x90
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/151137

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

풀이)

SELECT car_type, count(*) as cars
from car_rental_company_car
where options like '%통풍시트%' 
    or options like '%열선시트%' 
    or options like '%가죽시트%'
group by car_type
order by car_type;

처음에 냅다 options in ('통풍시트', '열선시트', '가죽시트')...

이렇게 했는데,,, 안 된다는걸 깨달았다....

728x90
728x90

https://www.acmicpc.net/problem/15649

 

15649번: N과 M (1)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net

 

 

풀이)

import java.util.Scanner;

public class Main_BJ_15649_N과M1 {
    static boolean[] visited;
    static int[] arr;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        visited = new boolean[n];
        arr = new int[m];

        perm(n, m, 0);
    }
    private static void perm(int n, int m, int idx){
        if(idx == m){
            for(int i=0; i<m; i++){
                System.out.print(arr[i]+" ");
            }
            System.out.println();
            return;
        }

        for(int i=0; i<n; i++){
            if(visited[i])
                continue;

            visited[i] = true;
            arr[idx] = i+1;
            perm(n, m, idx+1);
            visited[i] = false;
        }
    }
}

오랜만에 순열 문제를 풀어보았다!!!

요즘 번아웃과,,,, 프로젝트와,,,, 바빠서 이제 푸는게 넘 슬플뿐...ㅠ

까먹은듯한 느낌인데... 다시 화이팅해서 문제 풀어야지이이이잉

화이팅!!

728x90

'코테 > 백준' 카테고리의 다른 글

백준 14889 스타트와 링크(JAVA)  (0) 2023.05.23
백준 4963 섬의 개수(JAVA)  (0) 2023.05.21
백준 1427 소트인사이드(JAVA)  (0) 2023.05.09
백준 1010 다리 놓기(JAVA)  (0) 2023.05.08
백준 14888 연산자 끼워넣기(JAVA)  (0) 2023.05.05
728x90

https://www.acmicpc.net/problem/1427

 

1427번: 소트인사이드

첫째 줄에 정렬하려고 하는 수 N이 주어진다. N은 1,000,000,000보다 작거나 같은 자연수이다.

www.acmicpc.net

 

 

 

풀이)

import java.util.Scanner;

public class Main_BJ_1427_소트인사이드 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String n = sc.next();
        int[] arr = new int[10];
        for(int i=0; i<n.length(); i++){
            char c = n.charAt(i);
            arr[(c-'0')]++;
        }
        for(int i=9; i>=0; i--){
            while(arr[i]>0) {
                System.out.print(i);
                arr[i]--;
            }
        }
    }
}

논리는 간단하다.

문자열에서 하나씩 찾고, 이를 숫자로 변환한 후 0부터 9까지의 배열에 개수를 저장해둔다.

숫자로 변환할 때는 char은 아스키코드로 변환되므로 '0'을 빼주면 깔끔하다!

배열에 숫자 개수를 저장해두면 큰 순서대로 개수만큼 출력하면 끝!!

 

아침에 간단하게 푼 문젱!!

728x90

'코테 > 백준' 카테고리의 다른 글

백준 4963 섬의 개수(JAVA)  (0) 2023.05.21
백준 15649 N과 M(1) (JAVA)  (1) 2023.05.16
백준 1010 다리 놓기(JAVA)  (0) 2023.05.08
백준 14888 연산자 끼워넣기(JAVA)  (0) 2023.05.05
백준 2156 포도주 시식(JAVA)  (4) 2023.05.03
728x90

https://www.acmicpc.net/problem/1010

 

1010번: 다리 놓기

입력의 첫 줄에는 테스트 케이스의 개수 T가 주어진다. 그 다음 줄부터 각각의 테스트케이스에 대해 강의 서쪽과 동쪽에 있는 사이트의 개수 정수 N, M (0 < N ≤ M < 30)이 주어진다.

www.acmicpc.net

 

 

 

풀이)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;

public class Main_BJ_1010_다리놓기 {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());
        StringTokenizer st;
        for(int tc=0; tc<t; tc++){
            st = new StringTokenizer(br.readLine());
            int n = Integer.parseInt(st.nextToken());
            int m = Integer.parseInt(st.nextToken());
            BigInteger[] arr = new BigInteger[31];
            arr[1] = BigInteger.ONE;
            for(int i=2; i<=30; i++){
                arr[i] = arr[i-1].multiply(BigInteger.valueOf(i));
            }
            if(n==m)
                System.out.println(1);
            else
                System.out.println(arr[m].divide(arr[n].multiply(arr[m-n])));
        }
    }
}

원래는 메모이제이션으로 조합 경우의 수를 저장하면 되는데,,,

이 문제는 간단하기 때문에 조합 공식(n! / m!(n-m)! 공식을 단순히 활용했다.

따라서,,, 팩토리얼 값만 bigInteger를 사용해서 저장해줘도....

정말 간단하게 해결할 수 있다..ㅎㅎ 야매같지만...ㅎ

 

https://st-lab.tistory.com/194

 

[백준] 1010번 : 다리 놓기 - JAVA [자바]

www.acmicpc.net/problem/1010 1010번: 다리 놓기 입력의 첫 줄에는 테스트 케이스의 개수 T가 주어진다. 그 다음 줄부터 각각의 테스트케이스에 대해 강의 서쪽과 동쪽에 있는 사이트의 개수 정수 N, M (0 <

st-lab.tistory.com

메모이제이션 참고 블로그!!

728x90

+ Recent posts