【CF962E】Byteland, Berland and Disputed Cities

Portal! --->

a few words

  There are three kinds of points on the number line (point B, point R, point P), now we need to connect some of them, so that after removing all B points, all P and R points are connected & after removing all R points , all points B and P are connected to two conditions, the cost of connecting the two points is the distance on the number line, and the minimum cost is obtained (read in the order of the position on the number line from small to large)


Solution

  this question. . It's actually a very mysterious greed

  First of all, there is a particularly direct idea, that is. . All B points are connected to its previous B point or P point, all R points are connected to its previous R point or P point, and P point is connected to the previous R point and the previous B point. Guaranteed to meet those two conditions and not detour too much

  However, if you draw a picture, you will find that there is actually a connection method that connects a P point with its previous P point, so that two sides can be omitted between the two P points (the connection between B and B is connected). One, one with R and R)Weak, I didn't expect this at first Q^Q

  Then the optimal solution should be to take the smaller of the two cases.

  

  For specific implementation, because the read-in is guaranteed to be in order, then all are connected according to the first method at the beginning. If there are currently two P points, then the optimal solution is taken with the second connection method, and the middle Just record the maximum value of the edge

  The code looks like this

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
const int MAXN=2*(1e5)+10,inf=2147483647;
ll ans;
int n,lastR,lastB,lastP,mxR,mxB;

int main(){
#ifndef ONLINE_JUDGE
    freopen("a.in","r",stdin);
#endif
    int x;
    char c;
    scanf("%d",&n);
    lastR=lastB=lastP=-inf;
    mxR=mxB=0;
    for (int i=1;i<=n;++i){
        scanf("%d %c\n",&x,&c);
        if (c=='R'||c=='P'){
            if (lastR!=-inf) 
                ans+=x-lastR,mxR=max(mxR,x-lastR);
            lastR=x; 
        }
        if (c=='B'||c=='P'){
            if (lastB!=-inf)
                ans+=x-lastB,mxB=max(mxB,x-lastB);
            lastB=x;
        }
        if (c=='P'){
            if (lastP!=-inf)
                ans+=min(0,x-lastP-mxR-mxB);
            lastP=x; mxR=mxB=0;
        }
    }
    printf("%I64d\n",ans);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324494729&siteId=291194637