比赛 ry分享赛 评测结果 AAAAAATTAT
题目名称 跳跳虎 最终得分 70
用户昵称 终焉折枝 运行时间 4.019 s
代码语言 C++ 内存使用 162.76 MiB
提交时间 2026-03-19 20:51:06
显示代码纯文本
#include<bits/stdc++.h>
using namespace std;

#define int long long
const int MAXN = 5005;
int n, d, T, a[MAXN];
const int INF = 1e18;
struct node{
	int i, h, g, f;
	bool operator > (const node &other)const{
		return f > other.f;
	}
};

int H(int i, int h){
	int dis = h - a[n];
	if(dis < 0) dis = -dis;
	int maxx = (n - i) * d;
	if(dis > maxx){
		return INF;
	}
	return 0;
}

void solve(){
	cin >> n >> d;
	for(int i = 1;i <= n;i ++){
		cin >> a[i];
	}
	if(abs(a[1] - a[n]) > (n - 1) * d){
		cout << "impossible\n";
		return;
	}
	vector<int> v;
	for(int i = 1;i <= n;i ++){
		for(int j = -n;j <= n;j ++){
			v.push_back(a[i] + j * d);
		}
	}
	sort(v.begin(), v.end());
	v.erase(unique(v.begin(), v.end()), v.end());
	priority_queue<node, vector<node>, greater<node> > q;
	map<int, int> mp[MAXN];
	q.push({1, a[1], 0, 0});
	mp[1][a[1]] = 0;
	while(!q.empty()){
		node u = q.top();
		q.pop();
		if(u.g > mp[u.i][u.h]) continue;
		if(u.i == n){
			if(u.h == a[n]){
				cout << u.g << '\n';
				return;
			}
		}
		int nxt = u.i + 1;
		auto L = lower_bound(v.begin(), v.end(), u.h - d);
		auto R = upper_bound(v.begin(), v.end(), u.h + d);
		for(auto it = L;it != R;it ++){
			int nxh = *it;
			if(abs(nxh - a[n]) > (n - nxt) * d) continue;
			int nxg = u.g + abs(nxh - a[nxt]);
			if(mp[nxt].find(nxh) == mp[nxt].end() || nxg < mp[nxt][nxh]){
				mp[nxt][nxh] = nxg;
				q.push({nxt, nxh, nxg, nxg + H(nxt, nxh)});
			}
		}
	}
	cout << "impossible\n";
}

signed main(){
	freopen("tiger.in", "r", stdin);
	freopen("tiger.out", "w", stdout);
	cin.tie(0) -> ios::sync_with_stdio(0);
	cin >> T;
	while(T --){
		solve();
	}
	return 0;
}