कठिन 0 हल किए गए 0% स्वीकृति

Longest Path in a DAG

Find the heaviest path in a task dependency graph.

आप क्या सीखेंगे

  • टोपोलॉजिकल सॉर्ट से कामों को क्रम देना
  • उसी क्रम में किनारों को रिलैक्स करना
  • DAG में सबसे भारी रास्ता ढूँढना

समस्या

Tasks 0..n−1 form a directed acyclic graph. Each edge [u, v, w] means task v can start w hours after task u. Find the length of the longest path (the critical path). Process nodes in topological order.

Implement longest_path(n, edges).

Input

n: The number of nodes. edges: Edges as [from, to, weight].

Output

Return the total weight of the longest path (0 if there are no edges).

सीमाएँ

1 ≤ n ≤ 100,000; 0 ≤ edges ≤ 200,000; 1 ≤ weight ≤ 10,000; the graph has no cycles

उदाहरण

उदाहरण 1
इनपुट:
n = 4
edges = [
    [0, 1, 3],
    [0, 2, 2],
    [1, 3, 4],
    [2, 3, 6]
]

अपेक्षित आउटपुट:
expected = 8
इनपुट:
long long n = 4;
std::vector<std::vector<long long>> edges = {
    {0, 1, 3},
    {0, 2, 2},
    {1, 3, 4},
    {2, 3, 6}
};

अपेक्षित आउटपुट:
long long expected = 8;
इनपुट:
long n = 4;
long[][] edges = new long[][] {
    new long[] {0, 1, 3},
    new long[] {0, 2, 2},
    new long[] {1, 3, 4},
    new long[] {2, 3, 6}
};

अपेक्षित आउटपुट:
long expected = 8;

व्याख्या

0→1→3 weighs 7, 0→2→3 weighs 8: the longest path is 8.

उदाहरण 2
इनपुट:
n = 3
edges = []

अपेक्षित आउटपुट:
expected = 0
इनपुट:
long long n = 3;
std::vector<std::vector<long long>> edges = {};

अपेक्षित आउटपुट:
long long expected = 0;
इनपुट:
long n = 3;
long[][] edges = new long[][] {};

अपेक्षित आउटपुट:
long expected = 0;

व्याख्या

Without edges every path has length 0.

कैसे हल करें

पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।

संकेत 1

क्योंकि graph में cycles नहीं हैं, हर node को उसके सभी predecessors process होने के बाद finalize किया जा सकता है.

संकेत 2

Nodes को topological order में रखें, फिर outgoing edges relax करके हर node तक best path length बनाएं.

संकेत 3

अगर graph में multiple components या कोई edges नहीं हैं, तो answer फिर भी longest reachable path weight दिखाना चाहिए.

अपेक्षित जटिलता

समय O(n + m), अतिरिक्त स्थान O(n + m)

संदर्भ

यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।