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 ll long long
#define db double
#define pairll pair<ll,ll>
#define lpairll pair<ll,pairll>
#define repp(i,a,b) for (ll i = a; i <= b; i++)
#define repz(i,a,b) for (ll i = a; i < b; i++)
#define repm(i,a,b) for (ll i = a; i >= b; i--)
#define fr first
#define sc second
#define mp make_pair
#define pb push_back
const ll N = 4e5+5, MOD = 1e9+7, M = 1e5+5;
ll tc = 1, n, m, lr[N], rr[N];
ll x, y, k, otsum, dg, dsum;
string s, s1, s2, ye = "YES", no = "NO";
vector<pairll> v;
ll kir[N], kan[N], val[N];
struct asdf{
ll l, r;
char a, b;
};
asdf stor[N];
void input(){
cin >> k >> n;
repp(i,1,n){
char A, B;
ll L, R;
cin >> A >> L >> B >> R;
if (L > R) swap(L,R);
stor[i].a = A, stor[i].b = B, stor[i].l = L, stor[i].r = R;
if (A == B){
otsum += abs(L-R);
}
else{
otsum += 1;
dsum += abs(L-R);
v.pb(mp(L,0));
v.pb(mp(R,1));
}
}
}
void solve(){
if (k == 1){
sort(v.begin(),v.end());
ll cur = -1, num = 0;
for (auto i : v){
if (i.fr > cur){
cur = i.fr;
num++;
val[num] = cur;
}
if (i.sc == 0) lr[num]++;
if (i.sc == 1) rr[num]++;
}
ll ans = LLONG_MAX;
ll nyal = 0;
// repp(i,1,num){
// cout << i << " " << val[i] << " " << lr[i] << " " << rr[i] << endl;
// }
val[0] = val[1];
repp(i,1,num){
kir[i] = kir[i-1]+nyal*2*(val[i]-val[i-1]);
nyal += rr[i];
}
nyal = 0;
val[num+1] = val[num];
repm(i,num,1){
kan[i] = kan[i+1]+nyal*2*(val[i+1]-val[i]);
nyal += lr[i];
}
repp(i,1,num){
ans = min(ans,kir[i]+kan[i]);
//cout << i << " " << val[i] << " " << kir[i] << " " << kan[i] << endl;
}
if (num == 0) ans = 0;
cout << ans+otsum+dsum << endl;
}
else{
sort(v.begin(),v.end());
ll sz = v.size(), ans = LLONG_MAX;
repz(i,0,sz){
repz(j,i+1,sz){
ll cur = 0;
repp(q,1,n){
if (stor[q].a == stor[q].b) continue;
ll ta = abs(stor[q].r-v[i].fr)+abs(stor[q].l-v[i].fr);
ll tb = abs(stor[q].r-v[j].fr)+abs(stor[q].l-v[j].fr);
cur += min(ta,tb);
}
if (ans > cur){
ans = cur;
//cout << v[i].fr << " " << v[j].fr << " " << cur << endl;
}
}
}
if (sz == 0) ans = 0;
//cout << otsum << endl;
cout << ans+otsum << endl;
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
//cin >> tc;
while(tc--){
input();
solve();
}
}
# | 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... |