【删边问题——Tarjan求割边】

题目

并查集暴力代码 30p

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

const int N = 1e5+10;

int n, m;
int a[N], p[N];
ll ans = 1e18;
ll s[3];
bool st;

struct edge
{
    int a, b;
} e[N];

void init()
{
    for(int i = 1; i <= n; i++)
        p[i] = i;
}

int find(int x)
{
    if(p[x] != x) p[x] = find(p[x]);
    return p[x];
}

void check()
{
    int cnt = 0;
    
    int fir = find(1);
    for(int i = 1; i <= n; i++)
    {
        if(p[i] == i) cnt++;
        if(p[i] == fir) s[1] += a[i];
        else s[2] += a[i];
    }
    if(cnt == 2) st = true, ans = min(ans, abs(s[2] - s[1]));
}
int main()
{
    scanf("%d%d", &n, &m);
    
        
    for(int i = 1; i <= n; i++)
        scanf("%d", a+i);
        
    for(int i = 1; i <= m; i++)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        e[i] = {a, b};
    }
    
    for(int i = 1; i <= m; i++)
    {
        init(); s[1] = s[2] = 0;
        for(int j = 1; j <= m; j++)
        {
            if(i == j) continue;
            int a = e[j].a, b = e[j].b;
            int pa = find(a), pb = find(b);
            if(pa != pb) p[pa] = pb;
        }
    check();
    }
    
    if(st) printf("%lld", ans);
    else puts("-1");
}

正解

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

const int N = 2e5+10;
const int M = 4e5+10;

int n, m;
int a[N]; //权重
ll f[N]; //子树权重和
int h[N], e[M], ne[M], idx; //链式前向星
ll sum, ans = 1e18; //权重和 答案
int dfn[N], low[N], tot; //时间戳 追溯值 分配器
bool flag; //割边存在性

void add(int a, int b)
{
	e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void tarjan(int u, int ine)
{
	dfn[u] = ++tot, low[u] = tot;
	f[u] = a[u];
	
	for(int i = h[u]; ~i; i = ne[i])
	{
		int j = e[i];
		if(!dfn[j])
		{
			tarjan(j, i);
			f[u] += f[j];
			low[u] = min(low[u], low[j]);
			if(low[j] > dfn[u]) //这里放在向下的部分,因为dfn[u]是固定的,向上的部分只会影响到low[u]
			{
				ans = min(ans, abs(sum - 2 * f[j]));
				flag = true;
			}
		}
		else if(i != (ine ^ 1))
			low[u] = min(low[u], dfn[j]);
	}
}
int main()
{
	scanf("%d%d", &n, &m);
	
		
	for(int i = 1; i <= n; i++)
	{
		scanf("%d", a+i);
		sum += a[i];
	}
	
	memset(h, -1, sizeof h);
	for(int i = 1; i <= m; i++)
	{
		int a, b;
		scanf("%d%d", &a, &b);
		add(a, b); add(b, a);
	}
	
	tarjan(1, -1); //调用时,第二个参数随便给
	
	if(f[1] != sum) ans = sum - 2 * f[1]; //不是连通图,直接求差(本题默认所给图最多两个连通分量)
	else
		if(!flag) ans = -1; //是连通图,无割边
	
	printf("%lld", ans); 
}
相关推荐
v_for_van9 分钟前
力扣刷题记录7(无算法背景,纯C语言)
c语言·算法·leetcode
先做个垃圾出来………15 分钟前
3640. 三段式数组 II
数据结构·算法
tankeven1 小时前
HJ93 数组分组
c++·算法
Σίσυφος19002 小时前
LM 在 PnP(EPnP / P3P)的应用
算法
陈天伟教授2 小时前
人工智能应用- 人工智能交叉:01. 破解蛋白质结构之谜
人工智能·神经网络·算法·机器学习·推荐算法
LightYoungLee2 小时前
General-behavior interview tutorials
算法
I_LPL3 小时前
day34 代码随想录算法训练营 动态规划专题2
java·算法·动态规划·hot100·求职面试
We་ct3 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:题解与思路解析
前端·算法·leetcode·链表·typescript
万象.3 小时前
redis集群算法,搭建,故障处理及扩容
redis·算法·哈希算法
plus4s3 小时前
2月19日(85-87题)
c++·算法