版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pengwill97/article/details/81951621
题意
从1为起点,找到一条有向路径,其经过节点和最大。
题解
tarjan算法缩点,形成有DAG,在DAG上DP即可,
代码
#include<bits/stdc++.h>
using namespace std;
typedef double db;
typedef long long ll;
typedef unsigned long long ull;
const int nmax = 1e6+7;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const ull p = 67;
const ull MOD = 1610612741;
int n, m;
int grass[nmax], ans[nmax], ss[nmax], nowans, st;
int head[nmax],head2[nmax], tot;
int dfn[nmax], low[nmax], color[nmax], scc, dfs_clock, tot2;
bool visit[nmax], instack[nmax], visitscc[nmax];
int newgrass[nmax];
struct edge {
int to, nxt;
}e[nmax << 1], e2[nmax << 1];
void add_edge(int u, int v) {
e[tot].to = v;
e[tot].nxt = head[u];
head[u] = tot ++;
}
void add_edge2(int u, int v) {
e2[tot2].to = v;
e2[tot2].nxt = head2[u];
head2[u] = tot2 ++;
}
void tarjan(int u) {
dfn[u] = low[u] = ++dfs_clock;
ss[st++] = u;
instack[u] = true;
for(int i = head[u]; i != -1; i = e[i].nxt) {
int v = e[i].to;
if(!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if(instack[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if(low[u] == dfn[u]) {
int temp = 0, now = 0;
scc ++;
while(now != u){
now = ss[--st];
instack[now] = false;
color[now] = scc;
temp += grass[now];
}
newgrass[scc] = temp;
}
}
void dfs(int u) {
visit[u] = true;
for(int i = head[u]; i != -1; i = e[i].nxt) {
int v = e[i].to;
if(!visit[v]) {
if(color[u] != color[v] ){
add_edge2(color[u], color[v]);
dfs(v);
} else
dfs(v);
} else if(color[u] != color[v]) {
add_edge2(color[u], color[v]);
}
}
}
void dfs2(int u) {
if(head2[u] != -1) {
for(int i = head2[u]; i != -1; i = e2[i].nxt) {
int v = e2[i].to;
dfs2(v);
ans[u] = max(ans[u], ans[v] + newgrass[u]);
}
} else {
ans[u] = newgrass[u];
}
}
int main(){
// freopen("in.txt", "r", stdin);
memset(head, -1, sizeof head);
memset(head2, -1, sizeof head2);
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; ++i) {
scanf("%d", &grass[i]);
}
for(int i = 1; i <= m; ++i) {
int u, v;
scanf("%d %d", &u, &v);
add_edge(u, v);
}
tarjan(1);
dfs(1);
dfs2(color[1]);
printf("%d\n", ans[color[1]]);
return 0;
}