홍시홍의 프로그래밍

[백준 2211] 네트워크 복구 본문

알고리즘 문제풀이/백준

[백준 2211] 네트워크 복구

홍시홍 2020. 2. 15. 17:19

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

 

2211번: 네트워크 복구

첫째 줄에 두 정수 N, M이 주어진다. 다음 M개의 줄에는 회선의 정보를 나타내는 세 정수 A, B, C가 주어진다. 이는 A번 컴퓨터와 B번 컴퓨터가 통신 시간이 C (1 ≤ C ≤ 10)인 회선으로 연결되어 있다는 의미이다. 컴퓨터들의 번호는 1부터 N까지의 정수이며, 1번 컴퓨터는 보안 시스템을 설치할 슈퍼컴퓨터이다. 모든 통신은 완전쌍방향 방식으로 이루어지기 때문에, 한 회선으로 연결된 두 컴퓨터는 어느 방향으로도 통신할 수 있다.

www.acmicpc.net

 

요구사항

1번 컴퓨터와 다른 컴퓨터를 최소 비용으로 연결하기

 

풀이

시작점이 주어졌으므로 다익스트라로 풀이한다

출력이 연결되는 간선이 어디에서 어디로 갔는가를 출력하는 것에서 고민을 했다ㅠㅠ

 

#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <functional>
//#include <bits/stdc++.h>

using namespace std;

int n, m;
int startcity, endcity;
struct go {
	int x;
	int y;
};
vector<go> v[1001];
int dist[1001];
go ans[1001];
void solve() {
	for (int i = 1; i <= n; i++) {
		dist[i] = 987654321;
	}
	priority_queue<pair<int,int>> q;
	dist[1] = 0;
	q.push({ 0,1 });
	while (!q.empty()) {
		int nowcity = q.top().second;
		int nowdist = -q.top().first;
		q.pop();
		for (int i = 0; i < v[nowcity].size(); i++) {
			int next = v[nowcity][i].x;
			int nextdist = v[nowcity][i].y;
			if (dist[next] > nowdist + nextdist) {
		//		cout << "nowcity" << nowcity << " " << next << endl;
				dist[next] = nowdist + nextdist;
				q.push({ -dist[next],next });
			//	ans.push_back({ nowcity,next });
				ans[next].x = nowcity;
				ans[next].y = next;
			}
		}
	}
}
int main() {
	cin >> n >> m;
	for (int i = 0; i < m; i++) {
		int x, y, z;
		scanf("%d%d%d", &x, &y, &z);
		v[x].push_back({ y,z });
		v[y].push_back({ x,z });
	}
	solve();
	cout << n - 1 << endl;
	for (int i = 2; i <= n; i++) {
		printf("%d %d\n", ans[i].x, ans[i].y);
	}

}

'알고리즘 문제풀이 > 백준' 카테고리의 다른 글

[백준 2110] 공유기 설치  (0) 2020.02.19
[백준 2512] 예산  (0) 2020.02.19
[백준 1213] 팰린드롬 만들기  (0) 2020.02.15
[백준 1431] 시리얼 번호  (0) 2020.02.15
[백준 1936] 소수 경로  (0) 2020.02.13
Comments