Hdu 3440(差分约束)

hdu 3440

差分约束,由于求最大差,故建立$a-b<=c$的不等式,跑最短路
h数组排序后,依次连接两个相邻的数,注意绝对值的问题

ps: INF要开0x7fffffff

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#define ms(i, j) memset(i, j, sizeof i)
#define FN2 "hdu3440" 
using namespace std;

const int MAXN = 1000 + 5, ZINF2 = 0x7fffffff;

struct edge
{
    int u, v, c;
}e[MAXN*MAXN];
struct house
{
    int no, hi;
    bool operator < (const house b) const 
    {
        return hi < b.hi;
    }
}h[MAXN];
struct sdc
{
    vector<int> G[MAXN];
    int dis[MAXN], cir[MAXN], vi[MAXN], n, en;
    void init(int n)
    {
        en = 0;
        this->n = n;
        for (int i=0;i<=n;i++) G[i].clear(), dis[i] = ZINF2, cir[i] = vi[i] = 0;
    }
    void addedge(int a, int b, int c)//a-b<=c
    {
        en++; e[en].u = b, e[en].v = a, e[en].c = c;
        G[b].push_back(en);
    }
    int solve(int from, int to)
    {
        queue<int> q;
        cir[from] = 1, vi[from] = true, dis[from] = 0, q.push(from);
        while(!q.empty())
        {
            int p = q.front(); q.pop(); vi[p] = false;
            for (int i=0;i<G[p].size();i++)
            {
                int v = e[G[p][i]].v, w = e[G[p][i]].c;
                if (dis[p]+w<dis[v])
                {
                    dis[v] = dis[p]+e[G[p][i]].c;
                    if (!vi[v])
                    {
                        vi[v] = true;
                        cir[v]++; if (cir[v]>n) return -1;
                        q.push(v);
                    }
                }
            }
        }
        return dis[to];
    }
}sd;

int n, d, kase = 0;

void init()
{
    scanf("%d%d", &n, &d);
    sd.init(n);
    for (int i=1;i<=n;i++)
    {
        scanf("%d", &h[i].hi);
        h[i].no = i;
    }
    sort(h+1, h+1+n);
}
void solve()
{
    for (int i=1;i<n;i++)
    {
        sd.addedge(i, i+1, -1);
        int u = min(h[i].no, h[i+1].no);
        int v = max(h[i].no, h[i+1].no);
        sd.addedge(v, u, d);
    }
    int u = min(h[1].no, h[n].no), v = max(h[1].no, h[n].no);
    printf("Case %d: %d\n", ++kase, sd.solve(u, v));
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen(FN2".in","r",stdin);
    freopen(FN2".out","w",stdout);
    #endif
    int t; scanf("%d", &t);
    while (t--)
    {
        init();
        solve();
    }
    return 0;
}
------ 本文结束 ------