#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<algorithm>
#include<limits.h>
#include<math.h>
#include<map>
#include<set>
#include<unordered_map>
#include<unordered_set>
#include<iomanip>
#include<cstring>
#include<random>
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
using namespace std;
vector<ll>calc(vector<pair<int,int>>arr){ // res[i] = how much would it cost if i setup 1 bridge for first i people
vector<int>pts;
for(auto[i,j]:arr){
pts.push_back(i);
pts.push_back(j);
pts.push_back((i+j)/2);
}
vector<ll>res(arr.size()+1,1e18);
for(int i=0;i<=(int)arr.size();i++){
for(int br:pts){
ll cr=0;
for(int j=0;j<i;j++){
cr+=abs(br-arr[j].first)+abs(br-arr[j].second);
}
res[i]=min(res[i],cr);
}
}
return res;
}
int cmp(pair<int,int>a,pair<int,int>b){
return a.first+a.second<b.first+b.second;
}
void solve(){
int k,n;
cin>>k>>n;
vector<pair<int,int>>arr;
ll res1=0;
for(int i=0;i<n;i++){
char c1,c2;
int a1,a2;
cin>>c1>>a1>>c2>>a2;
if(c1==c2){
res1+=abs(a1-a2);
}else{
res1++;
if(a1>a2)
swap(a1,a2);
arr.emplace_back(a1,a2);
}
}
sort(arr.begin(),arr.end(),cmp);
vector<ll>r1=calc(arr);
reverse(arr.begin(),arr.end());
vector<ll>r2=calc(arr);
ll res2=1e18;
if(k==1){
res2=r1.back();
}else{ // k == 2
for(int i=0;i<=(int)arr.size();i++)
res2=min(res2,r1[i]+r2[(int)arr.size()-i]);
}
cout<<res1+res2<<"\n";
}
int main(){
ios::sync_with_stdio(false);cout.tie(NULL);cin.tie(NULL);
//freopen("/Users/jakob/cp_testing/test.txt","r",stdin);//freopen("output.out","w",stdout);
int t=1;//cin>>t;
while(t--)solve();
return 0;
}
/*
1 5
B 0 A 4
B 1 B 3
A 5 B 7
B 2 A 6
B 1 A 7
24
2 5
B 0 A 4
B 1 B 3
A 5 B 7
B 2 A 6
B 1 A 7
22
*/
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
1 ms |
344 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
600 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |