HDU - 5438 Ponds 拓扑找环+dfs

题意:

 

思路:

用拓扑找环的方法,O(n) 把度数为1(跟其相连的点小于2)的点去掉,并标记,那样剩下一些环,然后dfs找每个环的权值和 和 环中结点的个数;将点个数为偶数的环去掉

其实这样做的话可以直接计算 有奇数个点的环的权值;

 

 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
const int maxn = 1e4 + 7;

int n, m;
ll v[maxn];
vector vec[maxn];
ll sum = 0;
int d[maxn];
bool vis[maxn];

void init() {
  scanf("%d%d", &n, &m);
    sum = 0;
    memset(vis, 0, sizeof vis);
    memset(d, 0, sizeof d);
    for(int i = 1; i <= n; ++i) {
      scanf("%lld", &v[i]);
      sum += (v[i]);
      vec[i].clear();
    }
    for(int i = 0; i < m; ++i) {
      int u, v; scanf("%d%d", &u, &v);
      vec[u].push_back(v);
      vec[v].push_back(u);
      d[u]++; d[v]++;
    }
}

ll dfs1(int id) {
  d[id]--;
  vis[id] = 1;
  ll res = v[id];
  for(auto i : vec[id]) {
    d[i]--;
    if(!vis[i] && d[i] < 2) {
      res += (dfs1(i));
    }
  }
  return res;
}

ll tmp, cnt;

void dfs2(int id) {
  vis[id] = 1;
  tmp += v[id], cnt += 1;
  for(auto i : vec[id]) {
    if(!vis[i]) {
      dfs2(i);
    }
  }
}

void solve() {
  for(int i = 1; i <= n; ++i) {
    if(vis[i]) continue;
    if(d[i] < 2) {
      sum -= dfs1(i);
    }
  }
  for(int i = 1; i <= n; ++i) {
    if(vis[i]) continue;
    tmp = 0, cnt = 0;
    dfs2(i);
    if(cnt%2 == 0) sum -= tmp;
  }
  printf("%lld\n", sum);
}

int main() {
  int T; scanf("%d", &T);
  while(T--) {
    init();
    solve();
  }
  return 0;
}

 

你可能感兴趣的:(DFS,拓扑)