糖果——差分约束 + 正环判定及其优化(手搓栈 + 标记法)

题目

思考

这里转为判定负环可以是可以,但是不能用超级源点了(改为把节点全部压入),因为按照题目条件,建立的应该是各个节点指向超级源点的有向边,这显然破坏了超级源点的功能

代码

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5+10, M = 3 * N;
int h[N], e[M], ne[M], idx, w[M];
int pre[N], col[N], cnt;
bool st[N];
int dist[N];
int q[N];
int n, k, hh, tt = -1;
ll ans;
void add(int a, int b, int c)  // 添加一条边a->b,边权为c
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
bool dfs(int u)
{
    if(col[u]) return col[u] == 2;
    col[u] = 2;
    if(~pre[u] && dfs(pre[u])) return true;
    col[u] = 1;
    return false;
}
bool check()
{
    memset(col, 0, sizeof col);
    for(int i = 0; i <= n; i++)
        if(!col[i] && dfs(i)) return true;
    return false;
}
bool spfa()
{
    memset(pre, -1, sizeof pre);
    memset(dist, -0x3f, sizeof dist);
    q[++tt] = 0, dist[0] = 0, st[0] = 1;
    
    while(hh <= tt)
    {
        int u = q[tt--];
        st[u] = 0;
        
        for(int i = h[u]; ~i; i = ne[i])
        {
            int j = e[i];
            if(dist[j] < dist[u] + w[i])
            {
                dist[j] = dist[u] + w[i];
                pre[j] = u;
                if(++cnt > n) 
                {
                    cnt = 0;
                    if(check()) return false;
                }
                if(!st[j])
                    q[++tt] = j, st[j] = 1;
            }
        }
    }
    
    for(int i = 1; i <= n; i++)
        ans += dist[i];
    return true;
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    
    cin >> n >> k;
    memset(h, -1, sizeof h);
    for(int i = 1; i <= k; i++)
    {
        int x, a, b;
        cin >> x >> a >> b;
        if(x == 1) add(a, b, 0), add(b, a, 0);
        else if(x == 2) add(a, b, 1);
        else if(x == 3) add(b, a, 0);
        else if(x == 4) add(b, a, 1);
        else add(a, b, 0);
    }
    for(int i = 1; i <= n; i++)
        add(0, i, 1);
    
    if(!spfa()) cout << "-1";
    else cout << ans;
}
相关推荐
郭涤生2 分钟前
AWB算法基础理解
人工智能·算法·计算机视觉
hetao17338373 分钟前
2026-01-21~22 hetao1733837 的刷题笔记
c++·笔记·算法
Hcoco_me5 分钟前
大模型面试题91:合并访存是什么?原理是什么?
人工智能·深度学习·算法·机器学习·vllm
2501_901147839 分钟前
零钱兑换——动态规划与高性能优化学习笔记
学习·算法·面试·职场和发展·性能优化·动态规划·求职招聘
充值修改昵称2 小时前
数据结构基础:B树磁盘IO优化的数据结构艺术
数据结构·b树·python·算法
程序员-King.8 小时前
day158—回溯—全排列(LeetCode-46)
算法·leetcode·深度优先·回溯·递归
月挽清风9 小时前
代码随想录第七天:
数据结构·c++·算法
小O的算法实验室9 小时前
2026年AEI SCI1区TOP,基于改进 IRRT*-D* 算法的森林火灾救援场景下直升机轨迹规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
小郭团队10 小时前
2_1_七段式SVPWM (经典算法)算法理论与 MATLAB 实现详解
嵌入式硬件·算法·硬件架构·arm·dsp开发
充值修改昵称10 小时前
数据结构基础:从二叉树到多叉树数据结构进阶
数据结构·python·算法