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 pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<long long, long long> pll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<long long> vl;
int k, n;
ll ans = 0;
vl ord;
ll pos[100100][2];
int main(){
ios_base::sync_with_stdio(false);
cin>>k>>n;
memset(pos, -1, sizeof pos);
for(int i = 0; i < n; i++){
char side1, side2;
ll p1, p2;
cin>>side1>>p1>>side2>>p2;
if(side1 == side2){
ans += abs(p1 - p2);
}
else
{
pos[i][0] = p1;
pos[i][1] = p2;
ord.pb(p1);
ord.pb(p2);
}
}
sort(ord.begin(), ord.end());
int sz = (int)ord.size();
if(ord.size() > 0 && k == 1){
ll pref[sz];
pref[0] = ord[0];
for(int i = 1; i < sz; i++)
pref[i] = pref[i-1] + ord[i];
ll best = 1e18;
for(int i = 0; i < sz; i++){
ll here = ans;
if(i+1 < sz)
{
here += pref[sz-1];
here -= pref[i];
here -= (sz - 1 - i) * ord[i];
}
if(i){
here -= pref[i-1];
here += i * ord[i];
}
here += (int)ord.size()/2;
best = min(best, here);
}
cout<<best<<endl;
return 0;
}
else if(ord.size() > 0 && k == 2){
ll best = 1e18;
for(int i = 0; i < sz; i++){
for(int j = i + 1; j < sz; j++){
// both bridges;
if(ord[i] == ord[j]) continue;
ll here = ans;
for(int s = 0; s < n; s++){
if(pos[s][0] == -1) continue;
ll mn = min(pos[s][0], pos[s][1]), mx = max(pos[s][0], pos[s][1]);
if(pos[s][0] <= ord[i] && pos[s][1] <= ord[i]){
here += 2 * ord[i] - pos[s][0] - pos[s][1] + 1;
//cout<<"BOTH LEFT: "<<mn<<" "<<mx<<" "<<2*ord[i] - mn - mx + 1<<" "<<ord[i]<<" "<<ord[j]<<endl;
}
else if(pos[s][0] >= ord[j] && pos[s][1] >= ord[j]){
here += pos[s][0] + pos[s][1] - 2*ord[j] + 1;
}
else if(mn<= ord[i] && mx >= ord[j]){
here += ord[i] - mn;
here += mx - ord[i];
here++;
}
else if(mn <= ord[i] && mx <= ord[j]){
here += ord[i] - mn;
here += mx - ord[i];
here++;
}
else if(mn <= ord[j] && mx >= ord[j]){
here += ord[j] - mn;
here += mx - ord[j];
here++;
}
else if(ord[i] <= mn && mx <= ord[j]){
ll small = mn + mx - 2 * ord[i] + 1, big = 2*ord[j] - mn - mx + 1;
here += min(small, big);
}
else
{
//cout<<mn<<" "<<mx<<" "<<i<<" "<<ord[i]<<" "<<ord[j]<<endl;
assert(false);
}
}
//if(here == 10) cout<<ord[i]<<" "<<ord[j]<<endl;
best = min(best, here);
}
}
cout<<best<<endl;
return 0;
}
cout<<ans<<endl;
return 0;
}
# | 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... |