Skip to content

[이준희-8주차 알고리즘 스터디] #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: junhee325/week8
Choose a base branch
from

Conversation

JHLEE325
Copy link
Contributor

@JHLEE325 JHLEE325 commented Mar 20, 2025

🚀 싸피 15반 알고리즘 스터디 8주차 [이준희]

📌 문제 풀이 개요

  • 이번 PR에서는 다음 5문제의 풀이를 포함합니다.
  • 각 문제에 대한 풀이 과정과 접근 방식을 설명합니다.

✅ 문제 해결 여부

  • 문제 1
  • 문제 2
  • 문제 3
  • 문제 4
  • 문제 5

💡 풀이 방법

문제 1: N과 M (9)

문제 난이도
실버 2

문제 유형
백트래킹

접근 방식 및 풀이
N과 M을 입력받고 N개의 수로 길이가 M인 모든 수열을 구하는 문제였습니다.
N개의 수 중 중복되는 숫자가 있을 수 있어서 처리하는 과정을 거쳤습니다.
문자열을 이용한 중복처리를 하였습니다.

if(cnt==M) {
			StringBuilder sb = new StringBuilder();
			for(int i=0;i<M;i++) {
				sb.append(res[i]+" ");
			}
			
			String seq = sb.toString().trim();
			
			if(!set.contains(seq)) {
				set.add(seq);
				System.out.println(seq);
			}
			
			return;
		}

문제 2: 트리의 부모 찾기

문제 난이도
실버 2

문제 유형
그래프 이론

접근 방식 및 풀이
노드와 그 정점을 이용하여 각 노드의 부모를 찾는 문제였습니다.
BFS를 활용하여 노드의 부모를 찾아 저장하고 출력하였습니다.

static void bfs(int start) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(start);
        isSelected[start] = true;
        
        while (!queue.isEmpty()) {
            int current = queue.poll();
            
            for (int neighbor : graph[current]) {
                if (!isSelected[neighbor]) {// 각 노드의 부모를 찾기 때문에 현재 노드로 부모 저장
                    isSelected[neighbor] = true;
                    res[neighbor] = current;
                    queue.add(neighbor);
                }
            }
        }
    }

문제 3: 구간 합 구하기 5

문제 난이도
실버 1

문제 유형
DP, 구간합

접근 방식 및 풀이
N*N 표의 숫자를 입력받고
지정된 좌표 사이의 구간합을 구하는 문제였습니다.
저장할 때 부터 DP를 이용하여 저장하고 조건에 따라 합을 구했습니다.

for(int i=1;i<=N;i++) {
        	st = new StringTokenizer(br.readLine());
        	for(int j=1;j<=N;j++) {
        		int tmp = Integer.parseInt(st.nextToken());
        		grid[i][j] = tmp + grid[i-1][j] + grid[i][j-1] - grid[i-1][j-1]; // DP를 사용하여 값 저장
        	}
        }
for(int i=0;i<M;i++) {
        	st = new StringTokenizer(br.readLine());
        	int x1 = Integer.parseInt(st.nextToken());
        	int y1 = Integer.parseInt(st.nextToken());
        	int x2 = Integer.parseInt(st.nextToken());
        	int y2 = Integer.parseInt(st.nextToken());
        	
        	int res = grid[x2][y2] - grid[x1-1][y2] - grid[x2][y1-1] + grid[x1-1][y1-1]; // 규칙에 따른 값 구하기
        	sb.append(res).append("\n");
        }

문제 4: 이진 검색 트리

문제 난이도
골드 4

문제 유형
그래프 이론, 그래프 탐색

접근 방식 및 풀이
트리의 전위순회 결과를 입력받으면 해당 트리의 후위순회 결과를 출력하는 문제였습니다.
트리의 조건으로 노드의 왼쪽 서브트리의 모든 키는 노드의 키보다 작다.
노드의 오른쪽 서브트리의 모든 키는 노드의 키보다 크다
라는 조건이 있었기 때문에 전위순회의 결과를 해당 규칙에 따라 트리를 구성한 후
후위순회 하였습니다.

if (stack.peek().num > tmp.num) { // 다음 출력되는 수가 현재 수보다 작다면
				stack.peek().lchild = tmp; // 왼쪽자식으로 저장
				stack.push(tmp);
			} else { // 크다면
				Node parent = null;
				while (!stack.isEmpty() && stack.peek().num < tmp.num) { // 그 노드의 적절한 위치 탐색
					parent = stack.pop();
				}
				parent.rchild = tmp; // 오른쪽 자식으로 저장
				stack.push(tmp);
			}

문제 5: 최단경로

문제 난이도
골드 4

문제 유형
다익스트

접근 방식 및 풀이
가중치가 있는 무향 그래프에서 시작점부터 각 노드까지의 최소비용을 구하는 문제였습니다.
다익스트라 알고리즘을 학습하여 풀이하였습니다.
다익스트라 알고리즘 중 priority queue를 활용하는 방식을 사용했습니다.

// 노드의 크기, 출발지
	public static void Dijkstra(int n, int start) { //다익스트라
		boolean[] check = new boolean[n + 1];
		int[] dist = new int[n + 1];
		int INF = Integer.MAX_VALUE;

		Arrays.fill(dist, INF);
		dist[start] = 0;

		PriorityQueue<Node> pq = new PriorityQueue<>(); // priorityqueue를 사용한 다익스트라
		pq.offer(new Node(start, 0));

		while (!pq.isEmpty()) {
			int curr = pq.poll().index;

			if (check[curr]) // 이미 방문했다면 패스
				continue;
			check[curr] = true;

			// index의 연결된 정점 비교
			for (Node next : graph[curr]) {
				if (dist[next.index] > dist[curr] + next.weight) { // 기존에 가는 비용이 새로 파악한 루트보다 큰 경우 최신화
					dist[next.index] = dist[curr] + next.weight;

					pq.offer(new Node(next.index, dist[next.index]));
				}
			}
		}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant