题目如下:
Betty owns a lot of ponds, some of them are connected with other ponds by pipes, and there will not be more than one pipe between two ponds. Each pond has a value vv.
Now Betty wants to remove some ponds because she does not have enough money. But each time when she removes a pond, she can only remove the ponds which are connected with less than two ponds, or the pond will explode.
Note that Betty should keep removing ponds until no more ponds can be removed. After that, please help her calculate the sum of the value for each connected component consisting of a odd number of pondsInput
The first line of input will contain a number T(1≤T≤30) which is the number of test cases.
For each test case, the first line contains two number separated by a blank. One is the number p(1≤p≤1e4) which represents the number of ponds she owns, and the other is the number m(1≤m≤105) which represents the number of pipes.
The next line contains p numbers v1,...,vp, where vi(1≤vi≤1e8) indicating the value of pond ii.
Each of the last mm lines contain two numbers aa and bb, which indicates that pond aa and pond bb are connected by a pipe.
思路:
题目要求将符合要求的点删除,计算每个 奇数点连通块 的权值之和
可以先通过拓扑算出每个点的度 同时 建图 + 并查集(连通块)
用优先队列经行bfs
优先队列(小根堆) 用 pair封装 {该点的度数,该点的标号}
找到符合的点就将其删除(注:这里容易假删除,导致后面还会计算这个点),在把该点连接的点遍历一下,连接点 度减一
... ...
AC代码如下:
#include <bits/stdc++.h>
#define buff \
ios::sync_with_stdio(false); \
cin.tie(0); \
cout.tie(0);
#define int long long
using namespace std;
const int N = 1e4 + 9;
int n, m, k;
int val[N];
int fa[N];
int d[N];
map<int, int> mp;
vector<pair<int, int>> s[N];
vector<int> g[N];
void init()
{
k = 0;
mp.clear();
for (int i = 1; i <= n; i++)
{
d[i] = 0;
fa[i] = i;
s[i].clear();
g[i].clear();
}
}
int find(int x)
{
return x == fa[x] ? fa[x] : fa[x] = find(fa[x]);
}
void solve()
{
cin >> n >> m;
init();
for (int i = 1; i <= n; i++)
{
cin >> val[i];
}
int u, v;
for (int i = 1; i <= m; i++)
{
cin >> u >> v;
d[u]++, d[v]++;
g[u].push_back(v), g[v].push_back(u);
u = find(u), v = find(v);
fa[v] = u;
}
for (int i = 1; i <= n; i++)
{
if (i == find(i))
{
mp[i] = ++k;
}
}
for (int i = 1; i <= n; i++)
{
s[mp[find(i)]].push_back({d[i], i});
}
int ans = 0;
// cout << k << " ***" << endl;
// for (int i = 1; i <= k; i++)
// {
// sort(s[i].begin(), s[i].end());
// }
for (int i = 1; i <= k; i++)
{
int sum = 0;
int cnt = s[i].size();
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
for (auto it : s[i])
{
q.push(it);
}
while (!q.empty())
{
auto it = q.top();
q.pop();
if (d[it.second] <= 1)
{
if (d[it.second] < 0)
continue;
cnt--;
d[it.second] = -1;
for (auto qq : g[it.second])
{
d[qq]--;
if (d[qq] <= 1)
q.push({d[qq], qq});
}
}
else
sum += val[it.second];
}
if (cnt & 1)
ans += sum;
}
cout << ans << '\n';
}
signed main()
{
int T;
cin >> T;
while (T--)
solve();
}