atcoder.jp

G - Longest Path / atcoder.jp

건이두 2020. 1. 1. 15:50
728x90

문제 링크 : https://atcoder.jp/contests/dp/tasks/dp_g
문제 해설 : https://jinpyo.kim/EducationalDP-solution
Submission : https://atcoder.jp/contests/dp/submissions/9268425
Java Source : https://github.com/skysign/WSAPT/blob/master/atcoder.jp/G%20-%20Longest%20Path/src/Main.java

Educational DP Contest에서 그래프 문제가 처음 나왔습니다. 우선 단어의 뜻을 잘 이해할 필요가 있습니다.

-directed : 한쪽 방향으로만 이라는 뜻이구요,

-edge가 1→2 이렇게 1에서 2로가는 것만 가능하다는 뜻입니다.

-cycle : 한번 방문했던 vertex들 중, 어느 것으로도 다시 방문하는 경우를 뜻합니다.

문제 풀 때가장 중요한 문구가, G does not contain directed cycles 입니다.
즉, edge가 1→2 2→3 이렇게 있고, 3→1 이런 edge는 존재하지 않는 다는 뜻입니다.

이부분을 놓쳐서, 저는 2차원의 dp[i][j]를 놓고, dp[i][j]는 i에서 시작해서 j로 도착하는 가장 긴 경우의 수, 라고 정의하고는, 잘 못된 방향으로 문제를 풀면서, 시간을 많이 낭비했네요.
문제에서 cycle이 없다고 정의 했기 때문에, edge의 순서대로 d[i]는 i번째 vertex에서 출발해서 끝까지 가는 가장 큰 길이로 정의 한뒤, 어떤 vertex 출발하는 edge가 복수개 있다고 한다면, 순서대로 다 가보고, 제일 긴패스를 선택하면 됩니다.

A부터 F번째 문제까지 오면서, DP를 2차원 배열로 푸는 방식에 너무 몰두한 나머지, 저는 문제를 올바르게 해석하지 못했었네요.

위의 문제 설명에서 적었듯이, i번째 vertex에서 갈 수 있는 vertex를 모두 방문하고, i번째 vertex의 longest path가 정해 지기 때문에 DFS(depth-first-search) 방식으로 트리를 방문하게 됩니다.

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

//  G - Longest Path / atcoder.jp
// 문제 링크 : https://atcoder.jp/contests/dp/tasks/dp_g
// 문제 해설 : https://jinpyo.kim/EducationalDP-solution
// Submission : https://atcoder.jp/contests/dp/submissions/9268425

public class Main {
    public static int N;
    public static int M;

    public static ArrayList<Integer> Vertices[];
    public static int dp[];

    public static void main(String[] args) throws IOException {
        Reader sc = new Reader();
//        Scanner sc = new Scanner(System.in);
        PrintWriter p = new PrintWriter(System.out);
        N = sc.nextInt();
        M = sc.nextInt();

        Vertices = new ArrayList[N + 1];
        dp = new int[N + 1];

        for(int i=1; i<=N; ++i)
            Vertices[i] = new ArrayList<>();

        for (int m = 1; m <= M; ++m) {
            int beg = sc.nextInt();
            int end = sc.nextInt();
            Vertices[beg].add(end);
        }

        int r = 0;

        for (int i = 1; i <= N; ++i) {
            if (Vertices[i].size() > 0) {
                r = Math.max(r, dfs(i));
            }
        }

        p.println(r);
        p.close();
    }

    public static int dfs(int idxBegVertex) {
        if(dp[idxBegVertex] > 0) {
            return dp[idxBegVertex];
        }

        for(int idxEndVertex: Vertices[idxBegVertex]) {
            dfs(idxEndVertex);
            dp[idxBegVertex] = Math.max(dp[idxBegVertex], dp[idxEndVertex] + 1);
        }

        return dp[idxBegVertex];
    }

    // https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String nextLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
}
728x90