프로그래밍 공부
작성일
2024. 3. 8. 16:50
작성자
WDmil
728x90

문제 설명

도넛 모양 그래프, 막대 모양 그래프, 8자 모양 그래프들이 있습니다. 이 그래프들은 1개 이상의 정점과, 정점들을 연결하는 단방향 간선으로 이루어져 있습니다.

 

크기가 n인 도넛 모양 그래프는 n개의 정점과 n개의 간선이 있습니다. 도넛 모양 그래프의 아무 한 정점에서 출발해 이용한 적 없는 간선을 계속 따라가면 나머지 n-1개의 정점들을 한 번씩 방문한 뒤 원래 출발했던 정점으로 돌아오게 됩니다. 도넛 모양 그래프의 형태는 다음과 같습니다.

 

크기가 n인 막대 모양 그래프는 n개의 정점과 n-1개의 간선이 있습니다. 막대 모양 그래프는 임의의 한 정점에서 출발해 간선을 계속 따라가면 나머지 n-1개의 정점을 한 번씩 방문하게 되는 정점이 단 하나 존재합니다. 막대 모양 그래프의 형태는 다음과 같습니다.

 

크기가 n 8자 모양 그래프는 2n+1개의 정점과 2n+2개의 간선이 있습니다. 8자 모양 그래프는 크기가 동일한 2개의 도넛 모양 그래프에서 정점을 하나씩 골라 결합시킨 형태의 그래프입니다. 8자 모양 그래프의 형태는 다음과 같습니다.

 

도넛 모양 그래프, 막대 모양 그래프, 8자 모양 그래프가 여러 개 있습니다. 이 그래프들과 무관한 정점을 하나 생성한 뒤, 각 도넛 모양 그래프, 막대 모양 그래프, 8자 모양 그래프의 임의의 정점 하나로 향하는 간선들을 연결했습니다.

그 후 각 정점에 서로 다른 번호를 매겼습니다.

이때 당신은 그래프의 간선 정보가 주어지면 생성한 정점의 번호와 정점을 생성하기 전 도넛 모양 그래프의 수, 막대 모양 그래프의 수, 8자 모양 그래프의 수를 구해야 합니다.

 

그래프의 간선 정보를 담은 2차원 정수 배열 edges가 매개변수로 주어집니다. 이때, 생성한 정점의 번호, 도넛 모양 그래프의 수, 막대 모양 그래프의 수, 8자 모양 그래프의 수를 순서대로 1차원 정수 배열에 담아 return 하도록 solution 함수를 완성해 주세요. 

제한사항

1 ≤ edges의 길이 ≤ 1,000,000

edges의 원소는 [a,b] 형태이며, a번 정점에서 b번 정점으로 향하는 간선이 있다는 것을 나타냅니다.

1 ≤ a, b ≤ 1,000,000

문제의 조건에 맞는 그래프가 주어집니다.

도넛 모양 그래프, 막대 모양 그래프, 8자 모양 그래프의 수의 합은 2이상입니다.

입출력 예

edges result
[[2, 3], [4, 3], [1, 1], [2, 1]] [2, 1, 1, 0]
[[4, 11], [1, 12], [8, 3], [12, 7], [4, 2], [7, 11], [4, 8], [9, 6], [10, 11], [6, 10], [3, 5], [11, 1], [5, 3], [11, 9], [3, 8]] [4, 0, 1, 2]

 


문제 해설

 

그래프 탐색의 기초를 물어보고, 각 그래프의 특징에 따라 구분을 할 수 있는지 물어보는 문제이다.

 

각 그래프 유형의 경우, 끝까지 갔을 때, 앞이 없다면 직선, 자기자신이 돌아오면 도넛, 아웃이 2개 이상 나타나면 8자형이된다.

 

여기까지면 평범한 문제인데, 이놈들이 제귀제한을 걸어놔서 일정 제귀 이상 반복되면 터지게 문제를 짜놓았다.

 

제귀나 while문으로 돌리는거나. 큰 차이는 없지만 스텍오버플로를 방지하기 위해 while문으로 돌리게 해놓게 짜야한다.

 

이럴꺼면 제귀로 풀면 안된다는 조건사항을 달아놔야지 참...


첫 번째 시도

#include <string>
#include <vector>

using namespace std;

class Point
{
public:
    Point() {}
    ~Point() {}
    int GetInEdgeSize() { return in_edge.size(); }
    int GetOutEdgeSize() { return out_edge.size(); }

    void InsertInEdge(const int& input) { in_edge.push_back(input); }
    void InsertOutEdge(const int& input) { out_edge.push_back(input); }
    
    const vector<int>& GetOutEdgeVector() { return out_edge; }
    
    int Move() { 
        if (out_edge.size() == 0)
            return -1;
        return out_edge[0]; 
    }

private:
    vector<int> in_edge;
    vector<int> out_edge;
};

int FindMax(const vector<vector<int>>& input) {
    int answer = 0;
    for (auto& def : input)
        answer = answer < max(def[0], def[1]) ? max(def[0], def[1]) : answer;
    return answer;
}

int ReturnToGraphShape(vector<Point>& graph, const int& now, const int& start)
{
    if (graph[now].GetOutEdgeSize() == 2) return 3;
    else if (graph[now].GetOutEdgeSize() == 0) return 2;
    else if (graph[now].Move() == start) return 1;

    ReturnToGraphShape(graph, graph[now].Move(), start);
}

int FindToStart(vector<Point>& graph) {
    for (int i = 0; i < graph.size(); i++)
        if (graph[i].GetInEdgeSize() == 0 && graph[i].GetOutEdgeSize() >= 2)
            return i;
}

vector<int> solution(vector<vector<int>> edges) {
    int max = FindMax(edges);

    vector<int> answer(4);
    vector<Point> graph(max);

    for (auto& def : edges)
    {
        graph[def[1] - 1].InsertInEdge(def[0] - 1);
        graph[def[0] - 1].InsertOutEdge(def[1] - 1);
    }

    answer[0] = FindToStart(graph) + 1;
    for (auto& def : graph[answer[0] - 1].GetOutEdgeVector())
        ++answer[ReturnToGraphShape(graph, def, def)];

    return answer;
}

실패

 

한번 직접 객체유형을 만들어서 비교해보려고 했으나, 비주얼스튜디오에서 동작시킬때는 정상동작하나, 폭파된다.

 

제귀를 쓰면 안되는거였다. 코드 로직 자체는 올바름.


두 번째 시도

#include <string>
#include <vector>
#include <map>

using namespace std;

map<int, vector<int>> Outgraph;
map<int, vector<int>> Ingraph;

int FindMax(const vector<vector<int>>& input) {
    int answer = 0;
    for (auto& def : input)
        answer = answer < max(def[0], def[1]) ? max(def[0], def[1]) : answer;
    return answer;
}

int ReturnToGraphShape(const int& now, const int& start)
{
    if (Outgraph[now].size() == 2) return 3;
    else if (Outgraph[now].size() == 0) return 2;
    else if (Outgraph[now][0] == start) return 1;

    ReturnToGraphShape(Outgraph[now][0], start);
}

int FindToStart() {
    for (int i = 0; i < Ingraph.size(); i++)
        if (Ingraph[i].size() == 0 && Outgraph[i].size() >= 2)
            return i;
}

vector<int> solution(vector<vector<int>> edges) {
    int max = FindMax(edges);

    vector<int> answer(4);
    for (int i = 0; i < max; i++)
    {
        Outgraph[i];
        Ingraph[i];
    }

    for (auto& def : edges)
    {
        Ingraph[def[1] - 1].push_back(def[0] - 1);
        Outgraph[def[0] - 1].push_back(def[1] - 1);
    }

    answer[0] = FindToStart() + 1;
    for (auto& def : Outgraph[answer[0] - 1]) ++answer[ReturnToGraphShape(def, def)];

    return answer;
}

실패

 

새로 유형을 만든게 문제인것 같아. Map형태로 다시 만들어서 구현했다. 

Map형태의 데이터에 대해서도 정상동작하나, 코딩테스트 에서는 실패했다.


세 번째 시도

#include <string>
#include <vector>
#include <map>

using namespace std;

map<int, vector<vector<int>>> graph;

int FindMax(const vector<vector<int>>& input) {
    int answer = 0;
    for (auto& def : input)
        answer = answer < max(def[0], def[1]) ? max(def[0], def[1]) : answer;
    return answer;
}

int ReturnToGraphShape(const int& now, const int& start)
{
    if (graph[now][1].size() == 2) return 3;
    else if (graph[now][1].size() == 0) return 2;
    else if (graph[now][1][0] == start) return 1;

    ReturnToGraphShape(graph[now][1][0], start);
}

int FindToStart() {
    for (int i = 0; i < graph.size(); i++)
        if (graph[i][0].size() == 0 && graph[i][1].size() >= 2)
            return i;
}

vector<int> solution(vector<vector<int>> edges) {
    int max = FindMax(edges);

    vector<int> answer(4);
    for (int i = 0; i < max; i++)
        graph[i].resize(2);


    for (auto& def : edges)
    {
        graph[def[1] - 1][0].push_back(def[0] - 1);
        graph[def[0] - 1][1].push_back(def[1] - 1);
    }

    answer[0] = FindToStart() + 1;
    for (auto& def : graph[answer[0] - 1][1])
        ++answer[ReturnToGraphShape(def, def)];

    return answer;
}

실패

 

Map유형을 한개로 통합하여 돌렸다. 당연히 실패함


네 번째 시도

#include <string>
#include <vector>
#include <map>

using namespace std;

map<int, vector<vector<int>>> graph;

int FindMax(const vector<vector<int>>& input) {
    int answer = 0;
    for (auto& def : input)
        answer = answer < max(def[0], def[1]) ? max(def[0], def[1]) : answer;
    return answer;
}

int ReturnToGraphShape(int& now, const int& start)
{
    if (graph[now][1].size() == 2) return 3;
    else if (graph[now][1].size() == 0) return 2;
    else if (graph[now][1][0] == start) return 1;

    now = graph[now][1][0];
    return 0;
}

int FindToStart() {
    for (int i = 0; i < graph.size(); i++)
        if (graph[i][0].size() == 0 && graph[i][1].size() >= 2)
            return i;
}

vector<int> solution(vector<vector<int>> edges) {
    int max = FindMax(edges);

    vector<int> answer(4);
    for (int i = 0; i < max; i++)
        graph[i].resize(2);


    for (auto& def : edges)
    {
        graph[def[1] - 1][0].push_back(def[0] - 1);
        graph[def[0] - 1][1].push_back(def[1] - 1);
    }

    answer[0] = FindToStart() + 1;
    for (auto& def : graph[answer[0] - 1][1]) {
        int shape = 0;
        int now = def;
        while (shape == 0) shape = ReturnToGraphShape(now, def);
        ++answer[shape];
    }

    return answer;
}

성공

아주 간단한 방법으로 해결했는데, 제귀를 while로 바꿨다.

이럴꺼면 제귀를 처음부터 막던가..

728x90

'코딩테스트 문제 풀이 > 그래프 탐색' 카테고리의 다른 글

부대복귀  (0) 2024.04.29
배달  (1) 2024.04.09
순위  (0) 2024.01.30
가장 먼 노드  (0) 2024.01.17