Codeforces 967 C. Stairs and Elevators (dichotomy)

Keywords: iOS

Title Description

There are n floors, each floor has m districts, which need to go up and down stairs or elevators. It takes a unit time to move and climb a staircase between adjacent areas. The maximum speed of elevators is v floors per unit time. Now, what is the minimum time needed to move from y1 district on x1 floor to y2 district on x2 floor?

Solving problems

Assuming X1 < x2, first compare the stairs, find the nearest staircase on the left side of x1, any staircase between X1 and x2, and the nearest staircase on the right side of x2, and then compare the minimum values of three routes. Similarly, we can get the minimum value of elevator ride.

code implementation

#include<bits/stdc++.h>
#define IO ios::sync_with_stdio(false);\
    cin.tie(0);\
    cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 1e5+10;
#define INF 0x3f3f3f3f
int l[maxn],e[maxn];
int main()
{
    IO;
    int n,m,cl,ce,v;
    cin>>n>>m>>cl>>ce>>v;
    for(int i=0; i<cl; i++)
        cin>>l[i];
    for(int i=0; i<ce; i++)
        cin>>e[i];
    int q,x1,y1,x2,y2;
    cin>>q;
    while(q--)
    {
        int ans=INF;
        cin>>x1>>y1>>x2>>y2;
        if(x1==x2)
        {
            cout<<abs(y1-y2)<<endl;
            continue;
        }
        if(y1>y2)
            swap(y1,y2);
        int cha=abs(x1-x2);
        int lou,dian;

        lou=lower_bound(l,l+cl,y1)-l;
        if(l[lou]<y2&&l[lou]>y1) ans=min(ans,(y2-y1)+cha);
        else
        {
            if(lou<cl&&l[lou]>y1) ans=min(ans,(l[lou]-y2)+(l[lou]-y1)+cha);
            if(lou>0)
            {
                lou-=1;
                ans=min(ans,(y1-l[lou])+(y2-l[lou])+cha);
            }
        }

        dian=lower_bound(e,e+ce,y1)-e;
        int dt=cha/v+((cha%v)>0);
        if(e[dian]<y2&&e[dian]>y1) ans=min(ans,(y2-y1)+dt);
        else
        {
            if(dian<ce&&e[dian]>y1) ans=min(ans,(e[dian]-y2)+(e[dian]-y1)+dt);
            if(dian>0)
            {
                dian -=1;
                ans=min(ans,(y1-e[dian])+(y2-e[dian])+dt);
            }
        }
        cout<<ans<<endl;

    }
    return 0;
}

Posted by dgoosens on Tue, 05 Feb 2019 06:36:16 -0800