Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 플로이드와샬
- GIT
- 이분탐색
- Spring
- 백트래킹
- 구현
- 비트마스킹
- 크루스칼
- SWEA
- 2018 KAKAO BLIND RECRUITMENT
- 프로그래머스
- 다익스트라
- 백준
- 최소 신장 트리
- BFS
- 2020 KAKAO BLIND RECRUITMENT
- 플로이드 와샬
- 시뮬레이션
- 파이썬
- 브루트포스
- 2021 KAKAO BLIND RECRUITMENT
- 2020 카카오 인턴십
- 트라이
- 우선순위큐
- 2019 KAKAO BLIND RECRUITMENT
- 투 포인터
- 조합
- 스택
- 투포인터
- 로봇 청소기
Archives
- Today
- Total
개발조아
[BOJ/백준] 23034 조별과제 멈춰! 파이썬 본문
728x90
문제 링크 : https://www.acmicpc.net/problem/23034
23034번: 조별과제 멈춰!
교수님이 시험 기간에 조별 과제를 준비하셨다...! 가톨릭대학교의 조교 아리는 N명의 학생을 2개의 조로 구성하여 과제 공지를 하려 한다. 이때, 구성된 각 조의 인원은 1명 이상이어야 한다. 각
www.acmicpc.net
MST와 BFS로 풀었다.
처음에는 단순하게 MST 구성해서 가중치 합 구하고
x,y의 간선 정보만을 보고 빼주면 될줄 알고 제출했더니 틀렸다.
당연하다. 문제는 두개의 점을 기준으로 두개의 MST를 만드는 것이다. 그래서 모든점을 포함하는 MST를 구성하고, 두 점을 기준으로 두개의 MST로 나누어야한다.
따라서 두 점 사이의 간선 중 가중치가 가장 큰 것을 빼주면 두개의 MST가 생성된다.
그래서 BFS로 모든점에서 각 점까지 도달했을 때 거쳐간 간선 중 가중치가 가장 큰것을 구했다.
그리고 이정보를 가지고 MST의 가중치의 합에서 두 지점사이의 최대 가중치를 빼주었다.
from sys import stdin
from collections import deque
input = stdin.readline
n,m = map(int, input().split())
adj_list = [[] for _ in range(n+1)]
max_cost_board = [[-1]*(n+1) for _ in range(n+1)]
edges = []
for _ in range(m):
a,b,c = map(int, input().split())
edges.append((a,b,c))
edges.sort(key=lambda x:x[2])
parent = [i for i in range(n+1)]
def solv():
q = int(input())
total_cost = kruskal()
set_max_cost_board()
for _ in range(q):
a,b = map(int, input().split())
print(total_cost-max_cost_board[a][b])
def set_max_cost_board():
for start in range(1,n+1):
bfs(start)
def bfs(start):
global max_cost_board
max_cost_board[start][start] = 0
q = deque([(start,0)])
while q:
now, max_cost = q.pop()
for nxt, cost in adj_list[now]:
if max_cost_board[start][nxt] == -1:
tmp_max_cost = max(max_cost,cost)
max_cost_board[start][nxt] = tmp_max_cost
q.appendleft((nxt,tmp_max_cost))
def kruskal():
global adj_list
edge_count = 0
cost = 0
for a,b,c in edges:
if not is_same_parent(a,b):
union(a,b)
edge_count += 1
cost += c
adj_list[a].append((b,c))
adj_list[b].append((a,c))
if edge_count == n-1:
return cost
def find(target):
global parent
if parent[target] == target:
return target
parent[target] = find(parent[target])
return parent[target]
def union(a,b):
global parent
a = find(a)
b = find(b)
if a != b:
parent[a] = b
def is_same_parent(a,b):
return find(a) == find(b)
solv()
'알고리즘 > 백준' 카테고리의 다른 글
[BOJ/백준] 3108 로고 파이썬 (0) | 2021.12.10 |
---|---|
[BOJ/백준] 1553 도미노 찾기 파이썬 (0) | 2021.12.06 |
[BOJ/백준] 17472 다리 만들기 2 파이썬 (0) | 2021.12.03 |
[BOJ/백준] 2479 경로 찾기 파이썬 (0) | 2021.12.03 |
[BOJ/백준] 1944 복제 로봇 (0) | 2021.12.03 |