编程语言
首页 > 编程语言> > 算法学习笔记(1):差分约束

算法学习笔记(1):差分约束

作者:互联网

差分约束

问题类型描述

模型转换

思维递进

不等式组无解

为什么不能用Dijkstra

拓展

代码实现

#include <bits/stdc++.h>
#include <bits/extc++.h>
#include <unordered_map>
#include <unordered_set>
using namespace std;
using namespace __gnu_cxx;
using namespace __gnu_pbds;

#define debug(x) cerr << #x << ": " << x << '\n';
#define bd cerr << "----------------------" << el;
#define el '\n'
#define cl putchar('\n');
#define pb push_back
#define eb emplace_back
#define x first
#define y second
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define lop(i, a, b) for (int i = (a); i < (b); i++)
#define dwn(i, a, b) for (int i = (a); i >= (b); i--)
#define ceil(a, b) (a + (b - 1)) / b
#define ms(a, x) memset(a, x, sizeof(a))
#define INF 0x3f3f3f3f
#define db double
#define all(x) x.begin(),x.end()
#define cmax(a, b) a = max(a, b)
#define cmin(a, b) a = min(a, b)
#define reps(i, x) for (int i = 0; i < x.size(); i++)

typedef long long LL;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<db, db> PDD;
typedef vector<int> vci;

template <typename T>
inline void read(T &x)
{
    x = 0;
    T f = 1;
    char c = getchar();
    while (!isdigit(c))
    {
        if(c == '-')
            f = -1;
        c = getchar();
    }
    while (isdigit(c))
    {
        x = (x << 1) + (x << 3) + (c ^ 48);
        c = getchar();
    }
    x *= f;
}

const int N = 1e5 + 10, M = 2e6 + 10, B = 66, md = 1e9 + 7;
const double PI = acos(-1), eps = 1e-8;

int T, n, m;

vector<PII> g[N];
int vis[N], dis[N];
bool inq[N];


int main()
{
    read(n), read(m);
    queue<int> q;
    rep(i, 1, m)
    {   int u, v, w;
        read(v), read(u), read(w);
        g[u].pb({v, w});
    }
    rep(i, 1, n)
    {
        g[0].pb({i, 0}); //建立0到所有点的边
        //这个0只是一个偏移量,你改为任意值都可以
    }

    memset(dis, 0x3f, sizeof dis);
    dis[0] = 0;
    q.push(0);
    while(!q.empty())
    {
        int u = q.front();
        q.pop();
        vis[u] ++ ;
        inq[u] = false;
        if(vis[u] > n + 1)
        {
            cout << "NO";
            exit(0);
        }
        #define v g[u][i].first
        #define w g[u][i].second
        reps(i, g[u])
        {
            if (dis[v] > dis[u] + w)
            {
                dis[v] = dis[u] + w;
                if(!inq[v])
                {
                    inq[v] = true;
                    q.push(v);
                }
            }
        }
        #undef v
        #undef w
    }
    rep(i, 1, n)
    {
        cout << dis[i];
        if( i < n) cout << ' ';
    }
}

标签:xj,ck,xi,read,笔记,算法,差分,dis,define
来源: https://blog.csdn.net/Gh0st_Lx/article/details/122271507