Question: How long is the maximum distance from the lowest to the highest?
(1) (walking mode: H1-> H2-> ''' HN) Where H1 to HN increase progressively.
(2) the distance between adjacent (highly adjacent) trees is less than or equal to D.
Idea: Differential Constraint
Diagram:
(1): the distance between adjacent (highly adjacent) trees is less than or equal to D.
for(i=1;i<N;i++){u=Tnode[i].id;v=Tnode[i+1].id;if(u>v)//d[i]-d[i+1]<=DInsert(i+1,i,D);elseInsert(i,i+1,D); }
(2): the distance between adjacent trees (adjacent original coordinates) must be greater than or equal to 1.
for(i=1;i<=N;i++)hash[Tnode[i].id]=i;for(i=1;i<N;i++)Insert(hash[i+1],hash[i],-1);
Code:
/* Difference constraint (diagram) * // * AC code: 188 ms */# include <iostream> # include <map> # include <cstdlib> using namespace STD; # define maxn 1005 # define INF 1e10using namespace STD; struct edge {int V, W, next;} e [3 * maxn]; int head [maxn], ecnt; int stack [maxn], CNT [maxn], DIS [maxn]; bool instack [maxn]; int N, D, Scr, sink, top; struct tree {int H, ID;} tnode [maxn]; Map <int, int> hash; int CMP (const void * P1, const void * P2) {return (TREE *) P1) -> H- (TREE *) P2)-> H;} // d [v] <= d [u] + W (u, v); void insert (int u, int V, int W) {e [ecnt]. V = V; E [ecnt]. W = W; E [ecnt]. next = head [u]; head [u] = ecnt ++;} void Init () {int I, U, V; memset (Head,-1, sizeof (head); ecnt = 0; // hash. clear (); for (I = 1; I <= N; I ++) {scanf ("% d", & tnode [I]. h); tnode [I]. id = I;} qsort (tnode + 1, n, sizeof (tnode [0]), CMP); scr = tnode [1]. ID; sink = tnode [N]. ID; for (I = 1; I <= N; I ++) hash [tnode [I]. id] = I; for (I = 1; I <n; I ++) Insert (hash [I + 1], hash [I],-1); for (I = 1; I <n; I ++) {u = tnode [I]. ID; V = tnode [I + 1]. ID; If (u> V) // d [I]-d [I + 1] <= D insert (I + 1, I, d); else insert (I, I + 1, D) ;}} void spfa (int scr, int sink) {int I, U, V, W; memset (instack, false, sizeof (instack )); memset (CNT, 0, sizeof (CNT); for (I = 1; I <= N; I ++) dis [I] = inf; Top = 0; stack [top ++] = scr; instack [Scr] = true; // CNT [Scr] = 1; // The Key of WA (calculated after removal, this will calculate more) dis [Scr] = 0; while (top) {u = stack [-- Top]; instack [u] = false; CNT [u] ++; If (CNT [u]> N) {printf ("-1 \ n"); return ;} for (I = head [u]; I! =-1; I = E [I]. next) {v = E [I]. v; W = E [I]. w; If (DIS [v]> dis [u] + W) {dis [v] = dis [u] + W; If (! Instack [v]) {instack [v] = true; stack [top ++] = V ;}}} printf ("% d \ n ", dis [sink]);} int main () {While (scanf ("% d", & N, & D )! = EOF) {If (n = 0 & D = 0) break; Init (); If (SCR <sink) spfa (1, N ); else spfa (n, 1);} return 0 ;}