其他分享
首页 > 其他分享> > 缩点

缩点

作者:互联网

摘抄自

#include <bits/stdc++.h>

using namespace std;
#define debug(x) cout << #x << "=" << x << endl;
const int N = 1e4 + 5;
int n, m, cn, col[N];
int a[N], val[N], f[N], deg[N];
int top, stc[N], vis[N], dn, dfn[N], low[N];
vector<int> e[N], g[N];

void tarjan(int id) {
	
  vis[id] = 1, dfn[id] = low[id] = ++dn, stc[++top] = id;
  for (int it : e[id]) {
    if (!dfn[it])
      tarjan(it), low[id] = min(low[id], low[it]);
    else if (vis[it])
      low[id] = min(low[id], dfn[it]);
  }
  
  if (dfn[id] == low[id]) 
  {
    col[id] = ++cn;
    while (stc[top] != id)
     col[stc[top]] = cn, vis[stc[top--]] = 0;
     
    vis[id] = 0, top--;
  }
}
int main() {
	
  cin >> n >> m;
  
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  for (int i = 1; i <= m; i++) 
  {
    int u, v;
    scanf("%d%d", &u, &v);
    e[u].push_back(v);
  }
  for (int i = 1; i <= n; i++)
    if (!dfn[i]) tarjan(i);
    
  for (int i = 1; i <= n; i++) 
  {
    val[col[i]] += a[i];
    for (int it : e[i])
      if (col[i] != col[it]) 
      {
        g[col[i]].push_back(col[it]);
        deg[col[it]]++;
      }
  }
  queue<int> q;

  for (int i = 1; i <= cn; i++)
    if (!deg[i]) q.push(i);
    
  while (q.size()) 
  {
    int t = q.front();
    q.pop();
    f[t] += val[t];
    for (int it : g[t]) {
      f[it] = max(f[it], f[t]);
      if (!--deg[it]) q.push(it);
    }
  }
  int ans = 0;
  for (int i = 1; i <= cn; i++) ans = max(ans, f[i]);
  cout << ans << endl;
  return 0;
}

标签:缩点,int,top,vis,dfn,low,id
来源: https://www.cnblogs.com/ErFu/p/16514336.html