hack数据无法通过
查看原帖
hack数据无法通过
1164386
njumh楼主2024/8/7 11:32
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;

int n,ans;
struct node {
	int d = 0,pre = 0,nxt = 0,ord = 0;//d为数值,ord为该数值输入时的顺序数
} a[32768];
void del(int x) {
	int le = a[x].pre, rt = a[x].nxt;
	a[le].nxt = rt;
	a[rt].pre = le;
}
int find(int ord) {
	int now = 1;
	while (a[now].ord != ord)
	{
		now = a[now].nxt;
	}
	return now;
}
bool cmp(node x, node y) {
	return (x.d < y.d||(x.d == y.d && x.ord < y.ord));
}
int main()
{
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i].d;
		a[i].ord = i;
	}
	sort(a + 1, a + n + 1,cmp);
	for (int i = 1; i <= n; i++)
	{
		if (i < n)
		{
			a[i].pre = i - 1;
			a[i].nxt = i + 1;
		}
		else a[n].pre = n - 1;
	}
	for (int i = n; i >= 1; i--)//从后往前删除,计算这个数与其在链表中相邻元素的差的最小值
	{
		int now = find(i);
		int le = a[now].pre;
		int rt = a[now].nxt;
		if (le == 0)
		{
			ans += abs(a[rt].d - a[now].d);
		}
		else if(rt == 0) {
			ans += abs(a[le].d - a[now].d);
		}
		else ans += min(abs(a[le].d - a[now].d), abs(a[rt].d - a[now].d));
		del(now);
	}
	cout << ans << endl;
	return 0;
}
2024/8/7 11:32
加载中...