Submission #259328

#TimeUsernameProblemLanguageResultExecution timeMemory
259328shayan_pPalembang Bridges (APIO15_bridge)C++14
0 / 100
1 ms384 KiB
// And you curse yourself for things you never done

#include<bits/stdc++.h>

#define F first
#define S second
#define PB push_back
#define sz(s) int((s).size())
#define bit(n,k) (((n)>>(k))&1)

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;

const int maxn = 1e5 + 10, inf = 1e9 + 10;
const ll INF = 1e18;

ll sv[maxn];

int pt;
map<int, int> Ls, Rs;
set<int> All;
int CR, CL;
ll ANS;

int MAXL, MINR;

void restart(){
    MAXL = -inf, MINR = inf;    
    pt = -inf;
    Ls.clear(), Rs.clear(), All.clear();
    CR = CL = 0;
    ANS = 0;
}
ll add(int f, int s){
    MAXL = max(MAXL, f);
    MINR = min(MINR, s);
    Ls[f]++, Rs[s]++;
    All.insert(f), All.insert(s);
    if(MAXL <= MINR){
	return 0;
    }
    if(pt == -inf){
	pt = MINR;
	for(int x : All){
	    if(Ls.count(x) && pt < x)
		CL+= Ls[x];
	    if(Rs.count(x) && x <= pt)
		CR+= Rs[x];		
	}
    }
    if(s <= pt)
	CR++;
    if(pt < f)
	CL++;
    if(pt < f)
	ANS+= f - pt;
    if(s < pt)
	ANS+= pt - s;
    while(CR < CL){
	int nw = *All.upper_bound(pt);
	ANS+= 1ll * (nw - pt) * (CR - CL);
	if(Rs.count(nw))
	    CR+= Rs[nw];
	if(Ls.count(nw))
	    CL-= Ls[nw];
	pt = nw;
    }
    return ANS * 2;
}

int main(){
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie();

    int k, n;
    cin >> k >> n;
    ll sig = 0;
    vector<pii> inp;
    for(int i = 0; i < n; i++){
	char a, b;
	int l, r;
	cin >> a >> l >> b >> r;
	if(r < l)
	    swap(l, r);
	sig+= r-l;
	if(a != b){
	    sig++;
	    inp.PB({l, r});
	}
    }
    sort(inp.begin(), inp.end(), [](pii a, pii b){ return a.F + a.S < b.F + b.S; } );
    n = sz(inp);

    if(n == 0)
	return cout << sig << endl, 0;
    
    restart();
    for(int i = 0; i < n; i++){
	sv[i + 1] = add(inp[i].F, inp[i].S);
    }
    restart();    
    ll ans = INF;
    for(int i = n-1; i >= 0; i--){
	ans = min(ans, sig + sv[i] + add(-inp[i].S, -inp[i].F));
    }
    if(k == 1)
	ans = sig + sv[n];
    return cout << ans << endl, 0;
    
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...