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 fi first
#define se second
#define eb emplace_back
#define mt make_tuple
#define all(x) (x).begin(), (x).end()
#define MOD 1000000007
typedef long long ll;
typedef pair <int, int> ii;
typedef pair <ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef long double ld;
const ll INF=LLONG_MAX;
const int mxn=1e6+5;
bool DEBUG=0;
int n,k;
bool vis[mxn];
char hs[mxn],of[mxn];
int hos[mxn],off[mxn];
ll solve(ll bridge){
ll res = 0ll;
for(int i=0; i<n; i++){
if(!vis[i]){
if(off[i]>hos[i]){
if(hos[i]<=bridge&&bridge<=off[i]){
res += off[i]-hos[i]+1ll;
}else if(bridge<hos[i]){
res += hos[i]-bridge+off[i]-bridge+1ll;
}else{
res += bridge-hos[i]+bridge-off[i]+1ll;
}
}else{
if(off[i]<=bridge&&bridge<=hos[i]){
res += hos[i]-off[i]+1ll;
}else if(bridge<off[i]){
res += hos[i]-bridge+off[i]-bridge+1ll;
}else{
res += bridge-hos[i]+bridge-off[i]+1ll;
}
}
}
}
return res;
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
//freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);
cin >> k >> n;
ll ans = 0ll, mid = 0ll;
ll cnt = n*2;
for(int i=0; i<n; i++){
cin >> hs[i] >> hos[i] >> of[i] >> off[i];
if(hs[i]==of[i]){
ans += ll(abs(hos[i]-off[i]));
cnt-=2;
vis[i]=1;
}else{
mid += ll(hos[i])+ll(off[i]);
}
}
if(k==2)return 0;
mid/=cnt;
ans+=min({mid==1?INT_MAX:solve(mid-1),solve(mid),mid==1e9?INT_MAX:solve(mid+1)});
cout << ans << endl;
}
// READ & UNDERSTAND
// ll, int overflow, array bounds, memset(0)
// special cases (n=1?), n+1 (1-index)
// do smth instead of nothing & stay organized
// WRITE STUFF DOWN
# | 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... |