-
[Algorithm] 백준 13424 비밀 모임 - C++, 플로이드-와샬쾌락없는 책임 (공부)/알고리즘 문제풀이 2022. 3. 22. 11:50반응형
13424번: 비밀 모임
입력 데이터는 표준 입력을 사용한다. 입력은 T개의 테스트 데이터로 구성된다. 입력의 첫 번째 줄에 테스트 케이스의 개수를 나타내는 자연수 T가 주어진다. 각 테스트 케이스의 첫째 줄에는 방
www.acmicpc.net
#include <iostream> #include <vector> #include <limits> #include <algorithm> using namespace std; int roomCount, edgeCount; int roomDist[101][101]; int main(){ // init ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); // input int testcase; cin >> testcase; while (testcase--){ vector<int> friendRooms; // input cin >> roomCount >> edgeCount; for(int i = 1; i <= roomCount; i++){ for(int j = 1; j <= roomCount; j++){ if(i == j) roomDist[i][j] = 0; else roomDist[i][j] = 999999999; } } for(int i = 0; i < edgeCount; i++){ int a, b, c; cin >> a >> b >> c; roomDist[a][b] = c; roomDist[b][a] = c; } int friendCount; cin >> friendCount; for(int i = 0; i < friendCount; i++){ int input; cin >> input; friendRooms.push_back(input); } // floyid for(int via = 1; via <= roomCount; via++){ for(int from = 1; from <= roomCount; from++){ for(int to = 1; to <= roomCount; to++){ if(roomDist[from][to] > roomDist[from][via] + roomDist[via][to]) roomDist[from][to] = roomDist[from][via] + roomDist[via][to]; } } } // search room int answer = 999999999; int minRoomidx = -1; for(int i = 1; i <= roomCount; i++){ int thisRoomCost = 0; for(int j = 0; j < friendRooms.size(); j++){ thisRoomCost += roomDist[i][friendRooms[j]]; } if(answer > thisRoomCost){ answer = thisRoomCost; minRoomidx = i; } } cout << minRoomidx << '\n'; } }
플로이드 와샬로 풀이를 하면 간단하게 답이 나왔습니다.
1. 플로이드 와샬로 n-to-n 최단 거리를 만들어 준 뒤
2. 친구들에서 방으로 거리 최소를 구하기
를 무식하게 돌리면 빠르게 답이 나오는 문제입니다.
단 테스트케이스가 여러개 있으므로 이에 대한 초기화를 잘 해줘야 2번째 테스트 케이스부터 답이 잘 나오게 됩니다.
반응형'쾌락없는 책임 (공부) > 알고리즘 문제풀이' 카테고리의 다른 글
[Algorithm] 백준 17182 우주 탐사선 - C++, 플로이드 와샬 (0) 2022.03.25 [Algorithm] 백준 11562 백양로 브레이크 - C++, 플로이드 와샬 (0) 2022.03.23 [Algorithm] 백준 18233 민준이와 마산 그리고 건우 - C++, 다익스트라 (0) 2022.03.21 [Algorithm] 백준 5972 택배 배송 - C++, 다익스트라 (0) 2022.03.19 [Algorithm] 프로그래머스 행렬 테두리 회전 - C++ (0) 2022.03.17