This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
using ll = long long;
#define f first
#define s second
vector<pii> cross;
int N, K, MN, MX;
ll check1(int bridge) {
ll ret = 0;
for(auto [st, en]:cross) {
if(bridge<st) ret += (ll)st-bridge+en-bridge;
else if(bridge>en) ret += (ll)bridge-st+bridge-en;
else ret += (ll)en-st;
}
return ret;
}
ll check2(int br1, int br2) {
ll ret = 0;
for(auto [st, en]:cross) {
if((st<=br1&&br1<=en) || (st<=br2&&br2<=en)) ret += (ll)en-st;
else if(br2<st) ret += (ll)st-br2+en-br2;
else if(br1>en) ret += (ll)br1-st+br1-en;
else ret += min((ll)st-br1+en-br1, (ll)br2-st+br2-en);
}
return ret;
}
ll one() {
ll ret = 2e9;
for(int i=MN;i<=MX;i++) ret = min(ret, check1(i));
return ret;
}
ll two() {
ll ret = 2e9;
for(int i=MN;i<=MX;i++) for(int j=i+1;j<=MX;j++) ret = min(ret, check2(i, j));
return ret;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
cin>>K>>N;
ll ans = 0;
MN = 2e9, MX = -2e9;
for(int i=0;i<N;i++) {
char z1, z2;
int b1, b2;
cin>>z1>>b1>>z2>>b2;
if(z1==z2) {
ans += abs(b1-b2);
} else {
cross.push_back({min(b1, b2), max(b1, b2)});
MN = min(MN, cross.back().f);
MX = max(MX, cross.back().s);
}
}
ans += cross.size();
if(K==1) cout<<ans+one();
else cout<<ans+two();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |