删边问题
还行,用并查集暴力求解的话,能过30%,考试的时候就选她了!
丑陋的暴力并查集:30%
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
//先试试用暴力能骗多少分
#define ll long long
const int N = 2e5 + 2;
struct Edge
{
int x, y;
}edge[N];
int n, m;
ll val[N] = { 0 }; //点的权值
int pre[N] = { 0 };
int ans = 0x3f3f3f3f;
void init()
{
for (int i = 1; i <= n; i++)
pre[i] = i;
}
int find(int a)
{
int root = a;
while (pre[root] != root)
root = pre[root];
while (pre[a] != a)
{
int fa = pre[a];
pre[a] = root;
a = fa;
}
return root;
}
void join(int a, int b)
{
int fa = find(a), fb = find(b);
if (fa != fb) pre[fa] = fb;
}
int getcal()
{
int cnt = 0;
for (int i = 1; i <= n; i++)
if (pre[i] == i)
cnt++;
return cnt;
}
int getDist()
{
unordered_map<int, int>ump; //大哥号 和值
for (int i = 1; i <= n; i++)
ump[find(i)] += val[i];
auto it = ump.begin();
int x = (*it).second;
it++;
int y = (*it).second;
//cout << x << " " << y << endl;
return abs(x - y);
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> val[i];
for (int i = 0; i < m; i++)
cin >> edge[i].x >> edge[i].y;
//只选一条边删除
int f = 1; //表示是否有解
for (int i = 0; i < m; i++) //删除edge[i]
{
init();
for (int j = 0; j < m; j++)
{
if (i == j) continue;
join(edge[j].x, edge[j].y);
}
//cout << getcal() << endl;
if (getcal() == 2)
{
f = 0;
ans = min(getDist(), ans);
}
}
if (f) cout << -1;
else cout << ans;
return 0;
}
分析一下,为什么会超时——重复构图!因为每一次都是只删除一个边,所以完全没必要重新画个图,如果能实现单一修改就好了QWQ,但是并查集,关系网是很复杂的,如果不能重头开始捋,很容易出错。
这里引入一个新的算法:Tarjan算法
因为该算法对于我这种突击蓝桥杯的蒟蒻选手不是很友好,所以就不细讲,详情可看这篇博文: Tarjan算法超超超详解(ACM/OI)(强连通分量/缩点)(图论)(C++)-CSDN博客
再附上蓝桥网站上大佬@七里喜欢喵喵的代码:
#include<iostream>
using namespace std;
#include<algorithm>
#include<cmath>
#include<vector>
#define int long long
#define N (int)(2e5 + 10)
int n, m, dfn[N], low[N], tot, h[N], idx = 1, ans = 1e18, sum, s, a[N];
bool flag;
struct {
int v, ne;
}e[N * 2];
void add(int u, int v){
e[++idx] = {v, h[u]};
h[u] = idx;
}
void Tarjan(int x, int ine){
dfn[x] = low[x] = ++tot;
for (int i = h[x]; i; i = e[i].ne) {
int y = e[i].v;
if (!dfn[y]){
Tarjan(y, i);
a[x] += a[y];
low[x] = min(low[x], low[y]);
if (low[y] > dfn[x])
ans = min(ans, llabs(sum - 2 * a[y])), flag = true;
}
else if (i != (ine ^ 1)) low[x] = min(low[x], dfn[y]);
}
}
signed main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++){
cin >> a[i]; sum += a[i];
}
for (int i = 1; i <= m; i++){
int u, v; cin >> u >> v;
add(u, v), add(v, u);
}
Tarjan(1, 0);
if (a[1] != sum) cout << sum - 2 * a[1] << endl;
else {
if (flag) cout << ans << endl;
else cout << "-1" << endl;
}
return 0;
}
有兴趣的小伙汁可以琢磨琢磨~