Home > Back-end >  Directed acyclic graph (dag) has the longest path, oneself can run, submit OJ for Wrong Anwser, refe
Directed acyclic graph (dag) has the longest path, oneself can run, submit OJ for Wrong Anwser, refe

Time:09-24

description: and the longest path of directed acyclic graph, as there are multiple, the minimum output dictionary sequence,

Input: the first line of two integers n, m, said there are n nodes, number 1 ~ n. The next m lines, each line three integers a, b, weight,
Output: a number of space separated integers, are associated with a weight and the largest route. If there are multiple, minimum output dictionary sequence that route,



I code:
as follows
 # include & lt; Iostream> 
using namespace std;

Int DP (int I);
Void printPath (int I);
Int TopoSort arr (int *);

Int n=100000;
Int * dp=new int [n + 1);
Int * * G=new int * (n + 1),
Int * choice=new int [n + 1);//record the later the vertices of the longest path
Int * od=new int [n + 1);//out - degree

Int main () {
Int m;
cin> N & gt;> m;

for (int i=0; I & lt;=n; I + +)
G [I]=new int [n].
for (int i=0; I & lt;=n; I + +)
For (int j=0; J & lt;=n; J + +)
G [I] [j]=1;

for (int i=0; I & lt;=n; I + +) {
Od [I]=0;
Dp [I]=0;
Choice [I]=1;
}

Int a, b, price;
for (int i=0; I & lt; m; I + +) {
cin> A. & gt;> B & gt;> Price;
G [a] =price;
Od [a] + +;
}

Int * tp=new int [n + 1);
For (int I=n; I & gt;=1; I -)//zero outdegree topological sort
Tp [I]=TopoSort (od);

For (int I=n; I & gt;=1; I -)//in accordance with the topological sort of reverse, computing nodes in turn Max - path
Dp/tp [I]]=dp (tp [I]);

Int max_v=0;
Int max_l=0;
For (int I=1; I & lt;=n; I + +)
If (dp [I] & gt; Max_l) {
Max_l=dp [I];
Max_v=I;
}

PrintPath (max_v);

return 0;
}

Int DP (int I) {
If (dp [I] & gt; 0)
Return dp [I];

For (int j=1; J & lt;=n; J + +) {//traverse all out side I
If (G [I] [j].=1) {
Int temp=DP (j) + G [I] [j];
If (temp & gt; Dp [I]) {
Dp [I]=temp;
Choice [I]=j;
}
}
}

Return dp [I];
}

Void printPath (int I) {
cout While (choice [I]!=1) {
I=choice [I];
cout }
}

{int TopoSort arr (int *)
For (int I=n; I & gt;=1; I -)
If (arr==0) [I] {
Arr [I]=1;

For (int j=1; J & lt;=n; J + +)
If (G [j] [I]!=1)
Od [j] -;
return i;
}
}


[b] very grateful!!!!!!

Some other time and space constraints don't want to, just want to get the most basic Wrong Answer, thank!!!

CodePudding user response:

(q&a with question the way thank you! https://ask.csdn.net/questions/1068522).
  • Related