题目大意:给出一张地图,地图上有N个点,M条边
现在有一个人去给这张地图上的点分东西(这个人可以选择任意一点当起点),给出每个点收到东西的兴奋度,求兴奋度的最大值(同一个点可以重复经过,且经过点的时候不一定要分东西给这个点)
解题思路:先求强连通分量,并求出每个强连通分量内的最大兴奋度,接着缩点,用桥连接,形成一张新图
接着跑最长路,以每个入度为0的点为源点
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define N 30010
#define M 150010
#define INF 0x3f3f3f3f
#define min(a,b) ((a) < (b) ? (a) : (b))
#define max(a,b) ((a) > (b) ? (a) : (b))
struct Edge{
int to, next;
}E[M];
struct Node{
int x, y;
}node[M];
int n, m, tot, dfs_clock, scc_cnt, top;
int head[N], val[N], pre[N], sccno[N], lowlink[N], stack[N], cost[N], in[N], d[N];
bool vis[N];
void AddEdge(int u, int v) {
E[tot].to = v;
E[tot].next = head[u];
head[u] = tot++;
}
void init() {
for (int i = 0; i < n; i++) {
scanf("%d", &val[i]);
val[i] = max(val[i], 0);
}
memset(head, -1, sizeof(head));
tot = 0;
for (int i = 0; i < m; i++) {
scanf("%d%d", &node[i].x, &node[i].y);
AddEdge(node[i].x, node[i].y);
}
}
void dfs(int u) {
pre[u] = lowlink[u] = ++dfs_clock;
stack[++top] = u;
int v;
for (int i = head[u]; i != -1; i = E[i].next) {
v = E[i].to;
if (!pre[v]) {
dfs(v);
lowlink[u] = min(lowlink[u], lowlink[v]);
}
else if (!sccno[v]) {
lowlink[u] = min(lowlink[u], pre[v]);
}
}
if (pre[u] == lowlink[u]) {
scc_cnt++;
cost[scc_cnt] = 0;
while (1) {
v = stack[top--];
sccno[v] = scc_cnt;
cost[scc_cnt] += val[v];
if (u == v)
break;
}
}
}
int ans;
void SPFA(int u) {
d[u] = cost[u];
ans = max(d[u], ans);
queue<int> q;
q.push(u);
vis[u] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = head[u]; i != -1; i = E[i].next) {
int v = E[i].to;
if (d[v] < d[u] + cost[v]) {
d[v] = d[u] + cost[v];
ans = max(ans, d[v]);
if (!vis[v]) {
vis[v] = true;
q.push(v);
}
}
}
vis[u] = false;
}
}
void solve() {
memset(pre, 0, sizeof(pre));
memset(sccno, 0, sizeof(sccno));
dfs_clock = top = scc_cnt = 0;
for (int i = 0; i < n; i++)
if (!pre[i])
dfs(i);
memset(head, -1, sizeof(head));
memset(in, 0, sizeof(in));
tot = 0;
int u, v;
for (int i = 0; i < m; i++) {
u = sccno[node[i].x];
v = sccno[node[i].y];
if (u != v) {
AddEdge(u, v);
in[v]++;
}
}
ans = 0;
memset(d, 0, sizeof(d));
for (int i = 1; i <= scc_cnt; i++)
if (!in[i]) {
memset(vis, 0, sizeof(vis));
SPFA(i);
}
printf("%d\n", ans);
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
init();
solve();
}
return 0;
}