반응형

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

 

9470번: Strahler 순서

지질학에서 하천계는 유향그래프로 나타낼 수 있다. 강은 간선으로 나타내며, 물이 흐르는 방향이 간선의 방향이 된다. 노드는 호수나 샘처럼 강이 시작하는 곳, 강이 합쳐지거나 나누어지는 곳

www.acmicpc.net

 

각 노드의 상위 노드 순서 최댓값이 1개인지, 2개 이상인지 기억해주었습니다.

위상정렬을 이용하여 강의 근원부터 물이 흐르는 방향을 따라 모든 노드를 방문해주었습니다.

 

#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;

int t, k, m, p, a, b, node;
vector<int> graph[1001];
int indegree[1001];
int strahler[1001][2];

void init() {
	memset(indegree, 0, sizeof(indegree));
	memset(strahler, 0, sizeof(strahler));
	for (int i = 1; i <= m; i++) {
		graph[i].clear();
	}
}

int main() {
	scanf("%d", &t);
	while (t--) {
		scanf("%d %d %d", &k, &m, &p);
		init();
		queue<int> q;
		while (p--) {
			scanf("%d %d", &a, &b);
			graph[a].push_back(b);
			indegree[b]++;
		}
		for (int i = 1; i <= m; i++) {
			if (indegree[i] == 0) {
				q.push(i);
				strahler[i][0] = 1;
			}
		}
		while (!q.empty()) {
			node = q.front();
			q.pop();
			for (int i = 0; i < graph[node].size(); i++) {
				if (strahler[node][0] == strahler[graph[node][i]][0]) {
                    // 동일한 값이 2개 이상인 경우
					strahler[graph[node][i]][1] = 1; // 2개 이상임을 표시
				}
				else if (strahler[node][0] > strahler[graph[node][i]][0]) {
                    // 최댓값 업데이트
					strahler[graph[node][i]][0] = strahler[node][0];
					strahler[graph[node][i]][1] = 0;
				}
				if (--indegree[graph[node][i]] == 0) {
					q.push(graph[node][i]);
					strahler[graph[node][i]][0] += strahler[graph[node][i]][1];
				}
			}
		}
		printf("%d %d\n", k, strahler[node][0]);
	}
}
반응형

'Algorithm' 카테고리의 다른 글

백준 1689 : 겹치는 선분  (0) 2021.11.17
백준 2352 : 반도체 설계  (0) 2021.11.17
백준 15922 : 아우으 우아으이야!!  (0) 2021.11.17
백준 1726 : 로봇  (0) 2021.11.17
백준 16562 : 친구비  (0) 2021.11.17

+ Recent posts