题目分析
感觉之前在哪里写过这个题,有点像洛谷的 P1007 独木桥 (链接:https://www.luogu.org/problemnew/show/P1007)
由于两个人都需要实现同样的目的,而且情况一致,那么我们将这两个人当作一个整体,先让这个整体找到长度为1的带子,此过程中令找带子的移动距离最小即可,然后依次找完所有的带子
就是个贪心的思想,局部最优。
代码区
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int Max = 3e5 + 10;
const int inf = 0x3f3f3f3f;
ll pos[Max][3];//记录每种带子的位置
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
memset(pos, 0, sizeof(pos));
for(ll i = 0 ; i < 2 * n ; i++)
{
int v;
scanf("%d", &v);
pos[v][++pos[v][0]] = i;
}
ll a = 0, b = 0;
ll sum = 0;
for (int i = 1; i <= n; i++)
{
sum += min(abs(pos[i][1] - a) + abs(pos[i][2] - b), abs(pos[i][2] - a) + abs(pos[i][1] - b));
a = pos[i][1];
b = pos[i][2];
}
printf("%I64d\n", sum);
}
return 0;
}