반응형
문제 출처 :
https://www.acmicpc.net/problem/6416
알고리즘 분석 :
문제 해결에 필요한 사항
1. 구현
문제 정의를 읽어보면 다음과 같다.
1. 들어오는 간선이 하나도 없는 단 하나의 노드가 존재한다. 이를 루트(root) 노드라고 부른다.
2. 루트 노드를 제외한 모든 노드는 반드시 단 하나의 들어오는 간선이 존재한다.
3. 루트에서 다른 노드로 가는 경로는 반드시 가능하며, 유일하다. 이는 루트를 제외한 모든 노드에 성립해야 한다.
이 3가지를 이용하여 문제를 풀어보면 다음과 같다.
1. 루트노드 존재여부 및 루트노드가 유일한지 확인한다.
2. 진입차수가 무조건 1이어야 한다.(루트노드를 제외하고)
3. 엣지 + 1 == 노드 수인지 확인한다.
소스 코드 :
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | #include <iostream> #include <cstdio> #include <memory.h> #include <algorithm> using namespace std; int indegree[10002]; int outdegree[10002]; bool nodeChk[10002]; int main() { int tc = 1; int edge = 0; int maxNode = -1; int minNode = 987654321; int root = -1; bool chk = true; while (tc) { int a, b; scanf("%d %d", &a, &b); nodeChk[a] = nodeChk[b] = true; if (a == -1 && b == -1) break; if(a != 0 && b != 0) { maxNode = max({ maxNode, a,b }); minNode = min({ minNode, a,b }); } if (!a && !b) { // root노드 찾는과정, 이때 루트 2번발견되면 트리 x for (int i = minNode; i <= maxNode; i++) { if (indegree[i] == 0 && outdegree[i] != 0) { if (root != -1) chk = false; root = i; } } // 트리 정의 :: 진입차수 2개이상되는게 발견되면 트리 x for (int i = minNode; i <= maxNode; i++) if (indegree[i] >= 2) chk = false; // 노드 개수 카운트 int get = 0; for (int i = minNode; i <= maxNode; i++) if (nodeChk[i]) get++; // 트리 정의 :: 엣지 + 1 == 노드 if (edge + 1 != get) chk = false; // 트리 정의 :: 루트가 존재해야 한다. if (root == -1) chk = false; if (chk || !edge) printf("Case %d is a tree.\n", tc++); else printf("Case %d is not a tree.\n", tc++); memset(indegree, 0, sizeof(indegree)); memset(outdegree, 0, sizeof(outdegree)); memset(nodeChk, false, sizeof(nodeChk)); root = -1; edge = 0; maxNode = -1; minNode = 987654321; chk = true; continue; } indegree[b]++; outdegree[a]++; edge++; } return 0; } // This source code Copyright belongs to Crocus // If you want to see more? click here >> | Crocus |
반응형
'Applied > 알고리즘 문제풀이' 카테고리의 다른 글
[2810번] 컵홀더 (0) | 2017.09.21 |
---|---|
[11292번] 키 큰 사람 (0) | 2017.09.19 |
[14648번] 쿼리 맛보기 (0) | 2017.09.17 |
카카오 모의 테스트 풀이(주소 수록) (0) | 2017.09.15 |
[14699번] 관악산 등산 (0) | 2017.09.15 |