[20250713] BOJ / P4 / Home Sweet Home / 권혁준 #456
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
🧷 문제 링크
https://www.acmicpc.net/problem/33958
🧭 풀이 시간
40분
👀 체감 난이도
✏️ 문제 설명
정점 N개, 간선 M개에 간선에 가중치가 달려있는
단순 양방향 연결 그래프가 주어진다.이 그래프에서 1번 점과 n번 점 사이의 최단 거리를 dist[n]이라 한다.
이 그래프에 간선을 하나 추가했을 때,
단순 양방향 연결 그래프의 성질이 깨지지 않도록 하며, 모든 점 i에 대해 dist[i]의 값이 줄어들지 않도록 간선을 추가하는 경우의 수를 구해보자.🔍 풀이 방법
어떤 간선 (u, v, w)를 추가했다고 가정하자.$abs(dist[u] - dist[v]) <= w$ 여야 한다.
추가한 뒤에 모든 점의 dist[i] 값이 줄어들지 않으려면,
즉, 문제 조건에 따라$abs(dist[u] - dist[v]) <= w <= K$ 가 되도록 u, v, w를 잘 정해주는 것이 목적이다.
뜬금없지만, dist배열을 정렬시켜놓고 생각해보면 답을 어떻게 구해야 하는지 아주 잘 보인다.
정렬시킨 dist배열에서$dist[i] - dist[j] <= K$ 인 j를 잘 정하면, 정답의 개수에 $(i-j)*(K-dist[i]+1) - (dist[j] + ... dist[i-1])$ 만큼 더해지게 된다.
그리고 dist배열이 정렬되어 있으므로 이 i,j는 투 포인터로 쉽게 관리할 수 있다.
마지막으로,
단순 양방향 연결 그래프의 성질이 깨지게 되는 경우를 정답에서 제외시키면 된다.이 경우는 이미 존재하는 간선을 추가한 경우 뿐이고, O(M)에 처리 가능하다.
⏳ 회고
중간에 음수가 되는 경우를 고려하지 못해서 틀렸었다.
문제 진짜 좋은듯