[CodeUp] #4901-화살표 그리기(2019 정올1차 대비)

#include <iostream>
#include <vector>
#include <cstdlib>
#include <algorithm>
using namespace std;

vector<vector<int> > v;
vector<int> loc;

int compare(vector<int> v1,vector<int> v2){
    if(v1[1]==v2[1]){
        return v1[0] < v2[0];
    }
    return v1[1] < v2[1];
}

long long find(int s,int e){
    long long sum = 0;

    if(s==e){
        return sum;
    }

    for(int i=s+1;i<e;i++){
        sum += min(abs(v[i][0]-v[i-1][0]),abs(v[i][0]-v[i+1][0]));
    }
    
    sum += abs(v[s+1][0]-v[s][0])+abs(v[e][0]-v[e-1][0]);

    return sum;
}

int main(){
    int n;
    cin >> n;

    v.resize(n,vector<int> (2,0));
    loc.resize(n+10,0);

    for(int i=0;i<n;i++){
        cin >> v[i][0] >> v[i][1];
    }

    sort(v.begin(),v.end(),compare);

    int cnt = 1;

    for(int i=0;i<n-1;i++){
        if(v[i][1]!=v[i+1][1]){
            loc[cnt++] = i;
        }
    }
    loc[0] = -1;
    loc[cnt] = n-1;

    long long ans = 0;

    for(int i=0;i<cnt;i++){
        ans+=find(loc[i]+1,loc[i+1]);
    }

    cout << ans;
}

좋은 웹페이지 즐겨찾기