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 FAST_IO ios_base::sync_with_stdio(0); cin.tie(nullptr)
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define REP(n) FOR(O, 1, (n))
#define pb push_back
#define f first
#define s second
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vii;
const int MAXN = 100100;
const ll INF = (ll)1e17;
int k, nn, n;
ll s[MAXN], t[MAXN];
vl pts;
set<ll> tmp;
map<ll, int> toId;
ll ans;
ll closed[MAXN], notOpened[MAXN];
void conc () {
FOR(i, 1, n) {
tmp.insert(s[i]);
tmp.insert(t[i]);
}
ll id = 0;
for (ll x : tmp) {
pts.pb(x);
toId[x] = id;
id++;
}
}
void solve1 () {
//ll curMin = INF;
ll cur = 0;
notOpened[0] = n;
FOR(i, 1, n) {
notOpened[toId[s[i]]]--;
closed[toId[t[i]]]++;
}
FOR(i, 1, (int)pts.size()-1) {
notOpened[i] += notOpened[i-1];
closed[i] += closed[i-1];
}
int ch = 0;
FOR(i, 0, (int)pts.size()-1) {
if (closed[i] >= notOpened[i]) {
ch = pts[i];
break;
}
}
FOR(i, 1, n) {
cur += abs(s[i] - ch) + abs(t[i] - ch);
}
ans += cur;
cout << ans << "\n";
}
int main()
{
FAST_IO;
cin >> k >> nn;
FOR(i, 1, nn) {
char pp, qq;
ll ss, tt;
cin >> pp >> ss >> qq >> tt;
if (pp == qq) {
ans += abs(ss-tt);
} else {
n++;
ans++;
//ans += abs(ss-tt);
s[n] = min(ss,tt);
t[n] = max(ss,tt);
}
}
conc();
if (k == 1) {
solve1();
return 0;
} else {
solve1();
return 0;
}
return 0;
}
/*
in:
1 5
B 0 A 4
B 1 B 3
A 5 B 7
B 2 A 6
B 1 A 7
ans: 24
in:
2 5
B 0 A 4
B 1 B 3
A 5 B 7
B 2 A 6
B 1 A 7
ans: 22
*/
# | 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... |