D - Monument Tour 冬季集训补题

题目:https://vjudge.z180.cn/contest/418003#problem/D
题意:一辆汽车往右走,如果左右有景点,则去哪个地方然后再返回自己第一次选的路,然后继续往右。

#include <bits/stdc++.h>
#define lowbit(x) (x & (-x))
using namespace std;
const int mod = 1e9 + 7;
const int N = 2e5 + 50;
const int INF = 0x3f3f3f3f;
typedef long long ll;
int maxn[N], minn[N];
int main()
{
    
    
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);

    memset(maxn, -1, sizeof(maxn));
    memset(minn, 0x3f, sizeof(minn));

    int n, m; cin >> n >> m;

    int k; cin >> k;
    while (k--) {
    
    
        int x, y; cin >> x >> y;
        maxn[x] = max(maxn[x], y);
        minn[x] = min(minn[x], y);
    }

    int a[N], cnt = 0;
    for (int i = 0; i < 100000; i++) {
    
     // 横路
        if (maxn[i] != -1) {
    
     // 标记
            a[cnt++] = minn[i], a[cnt++] = maxn[i];
        }
    }

    sort(a, a + cnt);

    ll ans = n - 1, mid = a[cnt / 2]; // 取中点, 这是规律, 也是sort的作用
    for (int i = 0; i < 100000; i++) {
    
    
        if (maxn[i] != -1) {
    
    
            ans += abs(maxn[i] - minn[i]) + abs(maxn[i] - mid) + abs(minn[i] - mid);
        }
    }

    cout << ans << endl;
    
    return 0;
}

为什么标记处:当maxn[i] == minn[i] 的时候还是要加上两遍呢, 其实是由ans的计算所决定的,因为有一个最大值和最小值之间的距离,那么所有的值应该统一起来,都应该是从一个点到另一个点,当两个点相等,就是指在一个点上的时候,那么所要加的长度是零。
另: 当从1 - cnt时, 中位数:a[(cnt + 1) / 2];
当从0 - cnt - 1 时, 中位数 : a[cnt / 2] ;

非常容易明白。

猜你喜欢

转载自blog.csdn.net/YingShen_xyz/article/details/112762063