天天看點

POJ - 3159 Candies(差分限制)

差分限制是把不等關系換成圖,求一個點減一個點的最大(最小)值;

對于公式a - b <= c;我們的問題是求一個點減一個點的最大值,作為邊的話,b->a的權值為c,求一遍最短路。

對于公式a - b >= c;我們的問題是求一個點減一個點的最小值,作為邊的話,b->a的權值為c,求一遍最長路。

具體問題具體分析,把數字轉化成點,不等關系轉換成邊就可以求解問題。

對于本題求解差的最大值,求一遍最短路即可。

代碼如下:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#define inf 0x3f3f3f3f

using namespace std;

const int maxn = 30005;
const int maxm = 150500;

int n, m, s, t;   //n為點數 s為源點
int head[maxn]; //head[from]表示以head為出發點的鄰接表表頭在數組es中的位置,開始時所有元素初始化為-1
int d[maxn]; //儲存到源節點的距離,在Spfa()中初始化
int cnt[maxn];
bool inq[maxn]; //這裡inq作inqueue解釋會更好,出于習慣使用了inq來命名,在Spfa()中初始化
int nodep;  //在鄰接表和指向表頭的head數組中定位用的記錄指針,開始時初始化為0

struct node {
    int v, w, next;
}es[maxm];

void init() {
    for(int i = 1; i <= n; i++) {
        d[i] = inf;
        inq[i] = false;
        cnt[i] = 0;
        head[i] = -1;
    }
    nodep = 0;
}

void addedge(int from, int to, int weight)
{
    es[nodep].v = to;
    es[nodep].w = weight;
    es[nodep].next = head[from];
    head[from] = nodep++;
}

bool spfa()
{
    stack<int> sta;
    d[s] = 0;    //s為源點
    inq[s] = 1;
    sta.push(s);
    while(!sta.empty()) {
        int u = sta.top();
        sta.pop();
        inq[u] = false;   //從queue中退出
        //周遊鄰接表
        for(int i = head[u]; i != -1; i = es[i].next) {  //在es中,相同from出發指向的頂點為從head[from]開始的一項,逐項使用next尋找下去,直到找到第一個被輸
                                                        //入的項,其next值為-1
            int v = es[i].v;
            if(d[v] > d[u] + es[i].w) { //松弛(RELAX)操作
                d[v] = d[u] + es[i].w;
                //pre[v] = u;
                if(!inq[v]) {      //若被搜尋到的節點不在隊列que中,則把to加入到隊列中去
                    inq[v] = true;
                    sta.push(v);
                    if(++cnt[v] > n) {
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

int main()
{
    int T, kcase = 0;
    while(~scanf("%d %d", &n, &m)) {
            init();
        int a, b, c;
        while(m--) {
            scanf("%d %d %d", &a, &b, &c);
            addedge(a, b, c);
        }
        s = 1;
        if(spfa()) {
            printf("%d\n", d[n]);
        }
    }
    return 0;
}