Hdu 3440(差分约束)

hdu 3440

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

ps: INF要开0x7fffffff

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#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;
}

------ 本文结束 ------