Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define int long long
- using ll = long long;
- #define f first
- #define s second
- using node = int;
- struct segtree{
- int size;
- vector<node> vals;
- node ne = 0; //a neutral element
- node comb(node a, node b){
- return max(a, b);
- }
- void init(int n){
- size = 1;
- while(size < n){
- size *= 2;
- }
- vals.assign(2 * size, ne);
- }
- void build(vector<node>& a, int x, int lx, int rx){ //build in O(N)
- if(rx - lx == 1){
- if(lx < a.size()){
- vals[x] = a[lx];
- }
- return;
- }
- int m = (lx + rx)/2;
- build(a, 2 * x + 1, lx, m);
- build(a, 2 * x + 2, m, rx);
- vals[x] = comb(vals[2 * x + 1],vals[2 * x + 2]);
- }
- void build(vector<node>&a){
- build(a, 0, 0, size);
- }
- void update(int i, node v, int x, int lx, int rx){
- if(rx - lx == 1){
- vals[x] = v;
- return;
- }
- int m = (lx + rx)/2;
- if(i < m)
- update(i, v, 2 * x + 1, lx, m);
- else
- update(i, v, 2 * x + 2, m, rx);
- vals[x] = comb(vals[2 * x + 1], vals[2 * x + 2]);
- }
- void update(int i, node v){
- update(i, v, 0, 0, size);
- }
- node query(int l, int r, int x, int lx, int rx){//query the range of [l to r-1]
- if(lx >= r || l >= rx)
- return ne;
- if(lx >= l && rx <= r){
- return vals[x];
- }
- int m = (lx + rx)/2;
- node s1 = query(l, r, 2 * x + 1, lx, m);
- node s2 = query(l, r, 2 * x + 2, m, rx);
- return comb(s1, s2);
- }
- node query(int l, int r){
- return query(l, r, 0, 0, size);
- }
- }st;
- const int mxP = 1e5 + 10;
- int n, p, yy[mxP], sp[mxP];
- pair<int, int> e[mxP];
- array<int, 4> a[mxP];
- bool cmp(int e1, int e2){
- if(a[e1][3] == a[e2][3])
- return a[e1][2] < a[e2][2];
- return a[e1][3] < a[e2][3];
- }
- bool cmp2(array<int, 4> e1, array<int, 4> e2){
- if(e1[2] == e2[2])
- return e1[3] < e2[3];
- return e1[2] < e2[2];
- }
- signed main(){
- ios_base::sync_with_stdio(0); cin.tie(0);
- //freopen("boards.in", "r", stdin); freopen("boards.out", "w", stdout);
- cin >> n >> p;
- st.init(p);
- for(int i=0; i < p; i++){
- for(int j=0;j < 4; j++)
- cin >> a[i][j];
- yy[i] = i;
- e[i] = {a[i][3], a[i][2]};
- }
- sort(a, a+p, cmp2);
- sort(yy,yy+p,cmp);
- sort(e, e+p);
- for(int i = 0; i < p; i++){
- sp[yy[i]] = i;
- }
- //for(int i=0; i < p; i++){
- //cerr << e[i].f << " " << e[i].s << "\n";
- //}
- for(int i=0;i<p; i++){
- int bx = a[i][2], by = a[i][3];
- int ax = a[i][0], ay = a[i][1];
- int pos = upper_bound(e, e + p, (pair<int, int>){ay, (ll)1e9}) - e;
- int sv = st.query(0, pos);
- //cerr << i << " " << bx << " " << by << " " << ax << " " << ay << " " << pos << " " << sv << "\n";
- //assert(sp[i]>=pos);
- if(sv >= 2 * n) assert(false); //CODE IS FAILING THIS ASSERT ON TEST CASES
- //assert(bx + by - (ay + ax - sv) >= 0);
- st.update(sp[i], bx + by - (ay + ax - sv));
- }
- //cerr << st.query(0, p) << "\n";
- cout << 2 * n - st.query(0, p) << "\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment