Skip to content

Conversation

@alirz-pixel
Copy link
Member

🚀 이슈 번호

Resolve: {#2331}

🧩 문제 해결

스스로 해결:

🔎 접근 과정

문제 해결을 위한 접근 방식을 설명해주세요.

  • 🔹 어떤 알고리즘을 사용했는지: 플로이드워셜 + 재귀
  • 🔹 어떤 방식으로 접근했는지

cost를 구하는 과정은 단순히 플로이드 와샬을 사용하였다.

이 과정에서 cost 갱신이 일어나는 것은 start-end 사이에 mid를 거쳐간다는 의미이므로 mid를 저장하도록 했다.
그리고 path를 저장하는 것은 반대로 저장해둔 start-mid-end를 탐색해야 하므로 재귀를 사용하여 path를 찾도록 했다.

image

⏱️ 시간 복잡도

시간 복잡도 분석을 작성해주세요.
최악의 경우 수행 시간은 어느 정도인지 분석합니다.

  • Big-O 표기법: O(N^3)
  • 이유:: 플로이드 와샬은 start, mid, end를 탐색하기 위해 반복문이 3번 사용되기 때문에 O(N^3)이 소요된다.

💻 구현 코드

#include <algorithm>
#include <iostream>
#include <vector>
#define INF 987654321

using namespace std;

struct Info {
	int cost;
	int vertex;
};

void print(vector<vector<int>>& graph) {
	for (int i = 0; i < graph.size(); i++) {
		for (int j = 0; j < graph.size(); j++) {
			cout << graph[i][j] << " ";
		}
		cout << "\n";
	}
	cout << "\n";
}

void find_path(vector<vector<Info>>& graph, vector<int>& path, int from, int to) {
	int mid = graph[from][to].vertex;
	if (from == mid || mid == -1) {
		path.push_back(from);
		return;
	}
	find_path(graph, path, from, mid);
	find_path(graph, path, mid, to);
}

int main() {
	int n, m;
	cin >> n >> m;

	vector<vector<Info>> graph(n, vector<Info>(n, { INF, -1 }));
	for (int i = 0; i < m; i++) {
		int a, b, cost;
		cin >> a >> b >> cost;

		a--; b--;
		if (graph[a][b].cost > cost) {
			graph[a][b] = { cost, a };
		}
	}
	
	for (int i = 0; i < n; i++) {
		graph[i][i].cost = 0;
	}


	// 플로이드 와샬 코드인데
	// 역추적을 어떻게 하면 되는거지?
	for (int mid = 0; mid < n; mid++) {
		for (int start = 0; start < n; start++) {
			for (int end = 0; end < n; end++) {
				if (graph[start][end].cost > graph[start][mid].cost + graph[mid][end].cost) {
					graph[start][end].cost = graph[start][mid].cost + graph[mid][end].cost;
					graph[start][end].vertex = mid; // start-end까지 가는데 mid를 거치는게 빠름
				}
			}
		}
	}

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			cout << ((graph[i][j].cost != INF) ? graph[i][j].cost : 0) << " ";
		}
		cout << "\n";
	}
	/*// === [DEBUG] ===
	cout << "\n";
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			cout << graph[i][j].vertex << " ";
		}
		cout << "\n";
	}
	cout << "\n";
	// === [DEBUG] === */

	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			if (i == j || graph[i][j].cost == INF) {
				cout << 0 << "\n";
				continue;
			}

			vector<int> answer;
			find_path(graph, answer, i, j);
			answer.push_back(j);

			cout << answer.size() << " ";
			for (auto e : answer)
				cout << e + 1 << " ";
			cout << "\n";
		}
		//cout << "\n";
	}

	return 0;
}

@alirz-pixel alirz-pixel self-assigned this Jan 26, 2026
@alirz-pixel alirz-pixel linked an issue Jan 26, 2026 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

260126 : 코딩테스트

2 participants