DP has two uses in Dags, one is the longest path (shortest way) of fixed and starting points
One of the longest paths is the algorithm of the critical Path (AOE).
Here is the code
#include <cstdio>#include<algorithm>#defineMAXN 2001using namespacestd;inta[Ten],HEAD[MAXN],N,P,F[MAXN],TP[MAXN],DE[MAXN],DS[MAXN];structss{intTo,w,last;} X[MAXN* +];voidAddintAintBintc) {x[++p].to=b; X[p].last=Head[a]; X[P].W=C; Head[a]=p;}intdpinta) { if(f[a]!=0)returnF[a]; if(!de[a])return 0; intv=head[a],t=0; while(v) {if(DP (X[V].TO) +x[v].w>t) {T=DP (x[v].to) +X[V].W; Ds[a]=x[v].to; } v=X[v].last; } F[a]=T; returnf[a];}void out(inta) { if(!a)return; out(Ds[a]); printf ("%d", a);}intMain () {scanf ("%d",&N); inta1,a2,a3; while(SCANF ("%d%d%d", &a1,&a2,&a3) = =3) {Add (A2,A1,A3); DE[A2]++; } intans=0, ANSV; for(intI=1; i<=n;i++) if(DP (i) >ans) {ans=DP (i); ANSV=i; } printf ("%d\n", ans); out(ANSV); return 0;}
About topological ordering (AOV) There are two algorithms, one is DFS, which uses the nature of the search tree, and then outputs the parent node after the output of its sub-nodes is finished.
And there's the broad search algorithm.
The code is given below
Dfs
#include <cstdio>#defineN 2000+10using namespacestd;intHead[n],num;structedge{intNext,to;} E[n* (n1)];intdfn[n][2],degree[n],ok=1, index,tot=0, topu[n];voidAddint from,intTo ) {e[++num].next=head[ from]; E[num].to=to ; head[ from]=num;}voidDfsintu) { if(!ok)return; dfn[u][0]=++index; for(intI=head[u];i;i=E[i].next) { intv=e[i].to; if(dfn[v][0]&&!dfn[v][1]) {ok=0;return;} Else if(!dfn[v][0]) {DFS (v); }} dfn[u][1]=++index; Topu[tot--]=u;}intMain () {intN; scanf ("%d",&N); intx, y; while(SCANF ("%d%d", &x,&y) = =2) {Add (x, y);d egree[y]++;} intflag=0; for(intI=1; i<=n;i++) { if(degree[i]==0) {x=i,flag=1;} } if(!flag) {printf ("NO");return 0;} Tot=N; for(intI=1; i<=n;i++) { if(!ok) Break; if(!dfn[i][0]/*&°ree[i]==0*/) Dfs (i); } if(ok==0) {printf ("NO");return 0;} for(intI=1; i<=n;i++) printf ("%d", Topu[i]); return 0;}
BFs
#include <cstdio>#include<algorithm>using namespacestd;intn,a,b,head[2001],num,z[2001],top,cl,op,deg[2001];structss{intLast,to;} e[2000000];voidAddintAintb) {e[++num].last=Head[a]; E[num].to=C; Head[a]=num;}voidBFs () {CL=1; while(cl<=top) { intm=z[cl],t=Head[m]; while(t) {deg[e[t].to]-=1; if(deg[e[t].to]==0) z[++top]=e[t].to; T=E[t].last; } CL+=1; }}intMain () {scanf ("%d",&N); while(SCANF ("%d%d", &a,&b) = =2) {Add (a, b); DEG[B]++; } for(intI=1; i<=n;i++) if(deg[i]==0) z[++top]=i; BFS (); if(top<n) printf ("NO"); Else for(intI=1; i<=top;i++) printf ("%d", Z[i]); return 0;}
Use of Dags: topological sequencing (AOV), Critical Path (AOE) and DP relationships