CF 542B -思维题

版权声明:欢迎随便转载。 https://blog.csdn.net/a1214034447/article/details/88319404

题目链接:http://codeforces.com/contest/1130/problem/B

解题思路:

因为是要两个人总和最小,所以只要保证每次两个人选择的总花费最少就好了。

#include<algorithm>
#include<cstdio>
#include <iostream>
#include <map>
using namespace std;
typedef long long ll;
const int mx = 2e5 + 10;
const int mod = 1e9 + 7;
int n,pos[mx];
bool vis[mx];
int main()
{
	scanf("%d",&n);
	int a;
	for(int i=1;i<=2*n;i++){
		scanf("%d",&a);
		if(vis[a]){
			pos[a+n] = i;
		}else pos[a] = i;
		vis[a] = 1;
	}
	int p1 = 1,p2 = 1,x,y;
	ll ans = 0;
	for(int i=1;i<=n;i++){
		int v = abs(p1-pos[i]) + abs(p2-pos[i+n]);
		x = pos[i] , y = pos[i+n];
		if(v>abs(p2-pos[i])+abs(p1-pos[i+n]))
		v = abs(p2-pos[i]) + abs(p1-pos[i+n]),swap(x,y);
		p1 = x, p2 = y;
		ans += v; 
	}
	printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a1214034447/article/details/88319404