Question: Given a directed acyclic graph, each node has the right value, starting from the point with zero inbound degree, and the point with zero outbound degree as the end point, the maximum possible weight at the end of the request (the weight value may be negative, but it cannot exceed int)
Idea: memory-based search. Many people do not know the benefits of reverse graph creation. I am still in normal order. The inbound degrees of each point are recorded in advance, and the maximum possible weights obtained from these points are enumerated.
The state transition equation of this question is well analyzed by dp [I] = v [I] + max (dp [u0], dp [u1], ......, dp [un]); u0 -- un is the node of the I connection. In addition, there are too many points, which are stored in an adjacent table.
#include <cstdio> #include <cstring> #include <iostream> #include <vector> #include <cmath> #define MAX 111111 #define INF 0x7FFFFFFF using namespace std; vector<int> edge[MAX]; int v[MAX],dp[MAX],deg[MAX]; int n,m; void init() { for(int i=0; i<=MAX; i++) { dp[i] = -INF; edge[i].clear(); } memset(deg,0,sizeof(deg)); } int dfs(int v0) { if(dp[v0] != -INF) return dp[v0]; int size = edge[v0].size(); if(size == 0) return v[v0]; int maxx = -INF; for(int i=0; i<size; i++) { int u = edge[v0][i]; maxx = max(maxx,dfs(u)); } return dp[v0] = v[v0] + maxx; } int main() { int i,j,a,b; while(scanf("%d%d",&n,&m) != EOF) { init(); for(i=1; i<=n; i++) { scanf("%d",&v[i]); } for(i=1; i<=m; i++) { scanf("%d%d",&a,&b); edge[a].push_back(b); deg[b] ++; } int maxx = -INF; for(i=1; i<=n; i++) { if(!deg[i]) { maxx = max(maxx,dfs(i)); } } printf("%d\n",maxx); } return 0; }