티스토리 뷰

Algorithm/BOJ

[C/C++] 백준 1865번 - 웜홀

poopooreum 2024. 4. 4. 20:06
반응형

✏️ 문제 링크

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

 

1865번: 웜홀

첫 번째 줄에는 테스트케이스의 개수 TC(1 ≤ TC ≤ 5)가 주어진다. 그리고 두 번째 줄부터 TC개의 테스트케이스가 차례로 주어지는데 각 테스트케이스의 첫 번째 줄에는 지점의 수 N(1 ≤ N ≤ 500),

www.acmicpc.net

 

✏️ 문제 설명

 

 

✏️ 문제 풀이

일반적으로 벨만-포드 알고리즘은 방문하는 노드의 거리배열값이 MAX라면 무시하고 지나가지만

이 문제의 경우에는 틀리게 됩니다. 자세한 내용은 아래 링크를 타고 들어가시면 될 것 같습니다.

시작점부터 도착점까지의 거리가 MAX가 아닌 dist[i]의 값이 i를 방문하지 않았다~라는 의미로 해석해야 됩니다

https://www.acmicpc.net/board/view/72951

 

글 읽기 - 1865번 빠진 조건 추가 요청입니다

댓글을 작성하려면 로그인해야 합니다.

www.acmicpc.net

 

✏️ 문제 코드

#include<iostream>
#include<tuple>
#include<vector>
#include<limits.h>
using namespace std;

typedef tuple<int, int, int>edge;
vector<long>dist;
bool time_travel(int n, vector<edge>edges);
int main() {

	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int T;
	cin >> T;

	for (int x = 0; x < T; x++) {

		vector<edge>tree;
		int N, M, W;
		cin >> N >> M >> W;

		dist.resize(N + 1);	
		fill(dist.begin(), dist.end(), INT_MAX);

		for (int i = 0; i < M; i++) {
			int start, end, time;
			cin >> start >> end >> time;
			tree.push_back(edge(start, end, time));
			tree.push_back(edge(end, start, time));
		}

		for (int i = 0; i < W; i++) {
			int start, end, time;
			cin >> start >> end >> time;
			tree.push_back(edge(start,end, -time));
		}

		dist[1] = 0;
		bool iscycle = time_travel(N, tree);

		if (iscycle)
			cout << "YES" << "\n";
		else
			cout << "NO" << "\n";	
	}
}
bool time_travel(int n,vector<edge>tree) {

	for (int i = 1; i < n; i++) {
		for (int j = 0; j < tree.size(); j++) {
			edge edges = tree[j];
			int start = get<0>(edges);
			int end = get<1>(edges);
			int time = get<2>(edges);
			if (dist[end] > dist[start] + time) {
				dist[end] = dist[start] + time;
			}
		}
	}

	for (int j = 0; j < tree.size(); j++) {
		edge edges = tree[j];
		int start = get<0>(edges);
		int end = get<1>(edges);
		int time = get<2>(edges);
		if (dist[end] > dist[start] + time) {
			return true;
		}
	}
	return false;
}

 

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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 31
글 보관함