uva12170 Easy Climb ACM/NWERC

#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<stdio.h>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<sstream>
#include<cassert>
using namespace std;
typedef long long LL;
const int maxn = 100 + 5;
const int maxx = maxn * maxn * 2;
const LL INF = (1LL << 60);
LL h[maxn], x[maxx], dp[2][maxx];
int main() {
	int T;
	cin >> T;
	while (T--) {
		int n;
		LL d;
		cin >> n >> d;
		for (int i = 0; i < n; i++)cin >> h[i];
		if (abs(h[0] - h[n - 1]) > (n - 1)*d) {
			cout << "impossible" << endl;
			continue;
		}
		int nx;
		for (int i = 0; i < n; i++) {
			for (int j = -n + 1; j <= n - 1; j++) {
				x[nx++] = h[i] + j * d;
			}
		}
		sort(x, x + n);
		nx = unique(x, x + nx) - x;

		int t = 0;
		for (int i = 0; i < nx; i++) {
			dp[0][i] = INF;
			if (x[i] == h[0])dp[0][i] = 0;
		}
		for (int i = 1; i < n; i++) {
			int k = 0;
			for (int j = 0; j < nx; j++) {
				while (k < nx&&x[k] < x[j] - d)k++;
				while (k + 1 < nx&&x[k + 1] < x[j] + d && dp[t][k + 1] <= dp[t][k])k++;
				if (dp[t][k] == INF) dp[t ^ 1][j] = INF; // (t, k) is not reachable
				else dp[t ^ 1][j] = dp[t][k] + abs(x[j] - h[i]);
			}
			t ^= 1;
		}
		for (int i = 0; i < nx; i++)
			if (x[i] == h[n - 1]) cout << dp[t][i] << "\n";
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值