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 int long long
#define pi pair<int, int>
#define pii pair<int, pi>
#define fi first
#define se second
#ifdef _WIN32
#define getchar_unlocked _getchar_nolock
#endif
int n, k;
vector<int> st, en;
bool vis[100005], vis2[100005];
int P[100005], S[100005];
vector<int> pos;
vector<pi> brute;
void solve(){
cin >> k >> n;
int ans = 0, tmp = 0;
for(int i=1;i<=n;i++){
char a, c; int b, d; cin >> a >> b >> c >> d;
if(a == c)ans += abs(b - d);
else st.push_back(max(b, d)), en.push_back(min(b, d)), tmp += abs(b - d) + 1, pos.push_back(b), pos.push_back(d), brute.push_back({b, d});
}
sort(st.begin(), st.end());
sort(en.begin(), en.end());
P[0] = (st.size() ? st[0] : 0);
int mn = (st.size() ? 1e18 : 0);
for(int i=1;i<(int)st.size();i++)P[i] = P[i-1] + st[i];
for(int i=(int)en.size()-1;i>=0;i--)S[i] = S[i+1] + en[i];
sort(pos.begin(), pos.end());
pos.erase(unique(pos.begin(), pos.end()), pos.end());
if(k == 2){
for(auto i : pos){
for(auto j : pos){
if(i >= j)continue;
int cur = 0;
for(auto [a, b] : brute){
int x = min(a, b), y = max(a, b);
if(x <= i && i <= y)continue;
if(x <= j && j <= y)continue;
cur += min(abs(i-a) + abs(i-b), abs(j-a) + abs(j-b));
cur -= abs(a - b);
}
mn = min(mn, cur);
}
}
cout << ans + tmp + mn;
return;
}
for(auto i : pos){
int cur = 0;
int x = upper_bound(st.begin(), st.end(), i) - st.begin();
if(x != 0){
x--;
cur += 2 * ((x + 1) * i - P[x]);
}
x = upper_bound(en.begin(), en.end(), i) - en.begin();
if(x != (int)en.size()){
cur += 2 * (S[x] - i * ((int)en.size() - x));
}
//cout << i << " " << cur << '\n';
mn = min(mn, cur);
}
cout << ans + tmp + mn;
}
main(){
ios::sync_with_stdio(0);cin.tie(0);
int tc = 1;
//cin >> tc;
for(int tc1=1;tc1<=tc;tc1++){
// cout << "Case #" << tc1 << ": ";
solve();
}
}
Compilation message (stderr)
bridge.cpp:72:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
72 | main(){
| ^~~~
# | 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... |