This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//#pragma GCC optimize("Ofast,O2,O3,unroll-loops")
//#pragma GCC target("avx2")
#include <bits/stdc++.h>
using namespace std;
void debug_out() { cerr << endl; }
template<typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
cerr << "[" << H << "]";
debug_out(T...);
}
#ifdef dddxxz
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif
#define SZ(s) ((int)s.size())
#define all(x) (x).begin(), (x).end()
#define lla(x) (x).rbegin(), (x).rend()
#define bpc(x) __builtin_popcount(x)
#define bpcll(x) __builtin_popcountll(x)
#define MP make_pair
clock_t startTime;
double getCurrentTime() {
return (double) (clock() - startTime) / CLOCKS_PER_SEC;
}
mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
typedef long long ll;
const int MOD = 1e9 + 7;
const int INF = 1000000101;
const long long LLINF = 1223372000000000555;
const int N = 1e6 + 3e2;
const int M = 5555;
long long Solve_One_Bridge(const vector<int> &a, const vector<int> &b){
vector<int> c;
for (int i : a) c.push_back(i);
for (int i : b) c.push_back(i);
sort(all(c));
long long res = 0;
int mid = c[(int)c.size() / 2 - 1];
for (int i : c) res += abs(i - mid);
return res;
}
void solve(int TC) {
int k, n;
cin >> k >> n;
long long ans = 0;
vector<int> a, b;
while (n--){
char p, q;
int x, y;
cin >> p >> x >> q >> y;
if (p == q){
ans += abs(x - y);
} else {
ans++;
a.push_back(x);
b.push_back(y);
}
}
n = a.size();
if (k == 1) {
cout << ans + Solve_One_Bridge(a, b) << endl;
return;
}
set<int> positions;
for (int i : a){
positions.insert(i - 1);
positions.insert(i);
positions.insert(i + 1);
}
for (int i : b){
positions.insert(i - 1);
positions.insert(i);
positions.insert(i + 1);
}
ll best = LLINF;
for (int x : positions){
for (int y : positions){
ll cur = 0;
for (int i = 0; i < n; i++){
cur += min(abs(a[i] - x) + abs(b[i] - x), abs(a[i] - y) + abs(b[i] - y));
}
best = min(best, cur);
}
}
cout << ans + best << endl;
}
int main() {
startTime = clock();
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
#ifdef dddxxz
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int TC = 1;
// cin >> TC;
for (int test = 1; test <= TC; test++) {
//debug(test);
//cout << "Case #" << test << ": ";
solve(test);
}
#ifdef dddxxz
cerr << endl << "Time: " << int(getCurrentTime() * 1000) << " ms" << endl;
#endif
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... |