//#define READ_NUM_TEST_CASES //#define ASSERTS // force asserts on online judge //#define OLD_COMPILER // (SOLUTION IS AT THE END OF THIS FILE) ////////////////////////// PROTOTYPING TEMPLATE ///////////////////////////////// // // Implementation: Adam Blaszkiewicz (atablash.pl), 2012-2014 /* This program is licensed under GNU General Public License version 3. See <http://www.gnu.org/licenses/>. */ // // // enable c++ iostream; only if no fastio //#define IOSTREAM //#define NO_UNLOCKED // fread_unlocked, fwrite_unlocked #define mp make_pair #define it iterator #define be begin() #define en end() #define sz size() #define fi first #define se second #define pub push_back #define puf push_front #define pob pop_back() #define pof pop_front() #define bs binary_search #define lb lower_bound #define ub upper_bound #define fo3(i,a,b) for(int i=(int)(a); i<(int)(b); ++i) #define of3(i,a,b) for(int i=(int)((b)-1); i>=(int)(a); --i) #define fo2(i,n) fo3(i,0,n) #define of2(i,n) of3(i,0,n) #define fo(...) VA_SEL(fo,__VA_ARGS__) #define of(...) VA_SEL(of,__VA_ARGS__) #define inl inline __attribute__ ((always_inline)) #define ninl __attribute__ ((noinline)) #ifdef OLD_COMPILER #include<vector> #include<map> #include<queue> #include<algorithm> #include<string> #include<stdint.h> #include<cstring> #include<iostream> #else #include<bits/stdc++.h> #endif #ifdef OLD_COMPILER #else #include<cstdint> #endif #include<utility> namespace ab{ typedef int8_t i8; typedef uint8_t ui8; typedef int16_t i16; typedef uint16_t ui16; typedef int32_t i32; typedef uint32_t ui32; typedef int64_t i64; typedef uint64_t ui64; // old: typedef i64 ll; typedef ui64 ull; typedef std::pair<i32,i32> pii; typedef unsigned int uint; typedef unsigned short ushort; typedef unsigned char uchar; struct VOID {}; template<typename I>struct FloatFrom{typedef VOID R;}; template<>struct FloatFrom<i32>{typedef double R;}; template<>struct FloatFrom<ui32>{typedef double R;}; template<>struct FloatFrom<i64>{typedef long double R;}; template<>struct FloatFrom<ui64>{typedef long double R;}; template<>struct FloatFrom<i16>{typedef float R;}; template<>struct FloatFrom<ui16>{typedef float R;}; template<>struct FloatFrom<i8>{typedef float R;}; template<>struct FloatFrom<ui8>{typedef float R;}; template<>struct FloatFrom<float>{typedef float R;}; template<>struct FloatFrom<double>{typedef double R;}; template<>struct FloatFrom<long double>{typedef long double R;}; template<typename I>struct Double{typedef VOID R;}; template<>struct Double<i8>{typedef i16 R;}; template<>struct Double<ui8>{typedef ui16 R;}; template<>struct Double<i16>{typedef i32 R;}; template<>struct Double<ui16>{typedef ui32 R;}; template<>struct Double<i32>{typedef i64 R;}; template<>struct Double<ui32>{typedef ui64 R;}; template<>struct Double<float>{typedef float R;}; template<>struct Double<double>{typedef double R;}; template<>struct Double<long double>{typedef long double R;}; #if defined __GNUC__ and ( __WORDSIZE == 64 ) typedef int128_t i128; typedef uint128_t ui128; template<>struct Double<i64>{typedef i128 R;}; template<>struct Double<ui64>{typedef ui128 R;}; #endif } #define FASTIO #ifdef NO_FASTIO #undef FASTIO #endif #ifdef DEBUG #undef NDEBUG #pragma message "Compiling in DEBUG mode." #undef FASTIO #ifdef _WIN32 #include<windows.h> inline void ec(int a){static HANDLE h=GetStdHandle(-12);SetConsoleTextAttribute(h,a?12:0xf);} inline void oc(int a){static HANDLE h=GetStdHandle(-11);SetConsoleTextAttribute(h,a?10:0xf);} #else // *nix includes for debug #endif #else #define NDEBUG #define ec(x) #define oc(x) #endif #include <cstdio> #include <cfloat> #ifdef OLD_COMPILER // TODO #else #include<type_traits> #endif #define _CAT(a,b) a##b #define CAT(a,b) _CAT(a,b) #define _10TH(a,b,c,d,e,f,g,h,i,CNT,...) CNT #define VA_CNT(...) _10TH(__VA_ARGS__,9,8,7,6,5,4,3,2,1) #define VA_SEL(a,...) CAT(a,VA_CNT(__VA_ARGS__))(__VA_ARGS__) #define _VA_GTONE(...) _10TH(__VA_ARGS__,1,1,1,1,1,1,1,1,0) #define VA_GTONE(a,...) CAT(a,_VA_GTONE(__VA_ARGS__))(__VA_ARGS__) #define foreach(e,c) for(__typeof((c).begin())e=(c).begin();e!=(c).end();++e) #define MIN_GCC(a,b,c) (__GNUC__ > (a) || \ (__GNUC__ == (a) && (__GNUC_MINOR__ > (b) || \ (__GNUC_MINOR__ == (b) && \ __GNUC_PATCHLEVEL__ >= (c))))) #define L0(str) fprintf(stderr,"%s:%d - " str "\n",__FILE__,__LINE__) #define L1(str,...) fprintf(stderr,"%s:%d - " str "\n",__FILE__,__LINE__,__VA_ARGS__) #define L(...) VA_GTONE(L,__VA_ARGS__) #ifdef NDEBUG #define D if(0) #define A(x) #define TEST_FLOAT(x) #define ASSERT_FLOAT(x) #else #define A(x) assert(x); #define _TEST_FLOAT(x) ((x) <= LDBL_MAX && (x) >= -LDBL_MAX) #define ASSERT_FLOAT(f) A(_TEST_FLOAT(f)) #define D #endif #define V(x) (E<<#x<<": "<<(x)<<N) #define XX {E<<"XX LINE "<<__LINE__<<N;} #if defined DEBUG or defined ASSERTS #undef NDEBUG #else #define NDEBUG #endif #ifdef _WIN32 // TODO #ifndef NO_UNLOCKED #define NO_UNLOCKED #endif //#define fread_unlocked _fread_nolock //#define fwrite_unlocked _fwrite_nolock #endif #define all(x) (x).be,(x).en #define type(x) __typeof(x) const char N='\n'; const char S=' '; using namespace std; using namespace __gnu_cxx; namespace ab{} using namespace ab; template<class T>inline T cbitl(T x,int i){return (x<<i) ^ (x>>(sizeof(T)*8-i));} namespace std{ #if defined __GNUC__ and not MIN_GCC(4,2,0) template<class T>struct hash<T>{} #endif // 1,2,last (!!!!!) template<>template<class A,class B>struct hash<map<A,B>>{ size_t operator()(const map<A,B>& m) const{ size_t r = m.size(); if(!r)return r; auto i=m.be; r^=hash<type(i)>()(i); ++i; r^=cbitl(hash<type(i)>()(*i),sizeof(r)*8/4); i=m.end(); --i; r^=cbitl(hash<type(i)>()(*i),sizeof(r)*8/2); return r; } }; template<>template<class A, class B>struct hash<pair<A,B>>{ size_t operator()(const pair<A,B>& p) const{ return hash<A>()(p.first) ^ cbitl(hash<B>()(p.second),sizeof(size_t)*8/2); } }; } #define rint _rint() #define ruint _ruint() #define rll _rll() #define rull _rull() #define rchar _rchar() #ifndef FASTIO inline void fin(int){}inline void fout(int){} #ifdef IOSTREAM inline int _rint(){int r;cin>>r;return r;} inline uint _ruint(){uint r;cin>>r;return r;} inline ull _rull(){ull r;cin>>r;return r;} inline char _rchar(){return cin.get();} template<typename T>inline void W(const T& i){cout<<i;} inline void W(){W('\n');} #else inline int _rint(){int r;scanf("%d",&r);return r;} inline uint _ruint(){uint r;scanf("%u",&r);return r;} inline ull _rull(){ull r;scanf("%llu",&r);return r;} inline ull _rll(){ll r;scanf("%lld",&r);return r;} inline char _rchar(){return getchar();} inline void W(char a='\n'){printf("%c",a);} inline void W(int a){printf("%d",a);} inline void W(uint a){printf("%u",a);} inline void W(const ull& a){printf("%llu",a);} inline void W(const ll& a){printf("%lld",a);} inline void W(const char *str){fputs(str,stdout);} inline void W(const double& d){printf("%.20f",d);} inline void W(const long double& d){printf("%.50Lf",d);} #endif #else #ifndef NO_UNLOCKED #define FREAD fread_unlocked #define FWRITE fwrite_unlocked #else #define FREAD fread #define FWRITE fwrite #endif // todo: test on pointers const int _IB=32768;const int _OB=32768; char _iB[_IB];int _iP = _IB;char _oB[_OB];int _oP = 0; inline void fin(int mc){int r=_IB-_iP;if(r>mc)return;fo(i,r)_iB[i]=_iB[i+_iP]; // TODO: memcpy FREAD(_iB+r,1,_iP,stdin);_iP = 0;} inline void fout(int mc){if(_OB-_oP>mc)return;FWRITE(_oB,1,_oP,stdout);_oP = 0;} inline void W(char c='\n'){_oB[_oP++]=c;} inline char _rchar(){return _iB[_iP++];} template<class T>inline T _rur(){ T r=0;char c=rchar; do c-='0',r=r*10+c,c=rchar;while(c>='0'); return r;} template<class T>inline T _rsi(){ char c=rchar; while(c<'-')c=rchar; if(c=='-')return -_rur<T>(); else{--_iP;return _rur<T>();}} template<class T>inline T _ru(){while(rchar<'0');--_iP;return _rur<T>();} inline int _rint(){fin(15);return _rsi<int>();} inline uint _ruint(){fin(15);return _ru<uint>();} inline ll _rll(){fin(25);return _rsi<ll>();} inline ull _rull(){fin(25);return _ru<ull>();} const int _rs = 20;char _r[_rs]; template<class T>inline void _w(T i){ if(numeric_limits<T>::is_signed && i<0)W('-'),i=-i; else if(i==0){W('0');return;} int pos = _rs; do{_r[--pos]='0'+i%10;i/=10;}while(i); do W(_r[pos]),++pos;while(pos<_rs);} inline void W(const int32_t& i){fout(15);_w(i);} inline void W(const uint32_t& i){fout(15);_w(i);} inline void W(const int64_t& i){fout(25);_w(i);} inline void W(const uint64_t& i){fout(25);_w(i);} inline void W(const char*str){int l=strlen(str);fout(l);memcpy(&_oB[_oP],str,l);_oP+=l;} inline void W(double d){fout(50);_oP+=sprintf(&_oB[_oP],"%.20f",d);} // todo #endif template<class A,class B>inline void W(const A&a,const B&b){W(a);W(b);} template<class A,class B,class C> inline void W(const A&a,const B&b,const C&c){W(a);W(b);W(c);} template<class A,class B,class C,class DD> inline void W(const A&a,const B&b,const C&c,const DD&dd){W(a);W(b);W(c);W(dd);} template<class T>inline void sortall(T&t){sort(t.be,t.en);} template<class T>inline void uniqall(T&t){t.resize(unique(t.be,t.en)-t.be);} inline int count1(uint i){return __builtin_popcount(i);} inline int count1(ull i){return __builtin_popcountll(i);} inline int parity(uint i){return __builtin_parity(i);} inline int parity(ull i){return __builtin_parityll(i);} inline int ilog(uint i){return 31-__builtin_clz(i);} // int log; floor(log2(i)) inline int ilog(ull i){return 63-__builtin_clzll(i);} #define powerof2(x) !(x&(x-1)) #define subset(a,b) (a&b==a) #define kbegin(k) ((1<<k)-1) #define kend(k,n) ((kbegin(k)<<n-k)+1) inline uint knext(uint a){uint b=(a|(a-1))+1;return b|((a^b)>>(__builtin_ctz(a)+2));} #define fors(x,k,n) for(uint x=kbegin(k);x<kend(k,n);x=knext(x)) template<class A,class B>inline ostream&operator<<(ostream&o,const pair<A,B>&p){o<<'<'<<p.fi<<", "<<p.se<<'>';return o;} template<class A,class B>inline ostream&operator<<(ostream&o,const map<A,B>&m){o<<N;for(auto&k:m)o<<"map["<<k.fi<<"] -> "<<k.se<<N;return o;} template<class A>inline ostream&operator<<(ostream&o,const vector<A>&_v){o<<N;fo(i,_v.sz)o<<"vector["<<i<<"] = "<<_v[i]<<N;return o;} struct _O{template<class T>_O&operator<<(const T&t){oc(1);W(t);oc(0);return*this;}}O; struct _I{ _I&operator>>(int32_t&t){t=rint;return*this;} _I&operator>>(uint32_t&t){t=ruint;return*this;} _I&operator>>(int64_t&t){t=rll;return*this;} _I&operator>>(uint64_t&t){t=rull;return*this;} }I; struct _E{template<class T>_E&operator<<(const T&t){D{ec(1);cerr<<t;ec(0);}return*this;}}E; inline void tc(); int main() { #ifdef FASTIO setvbuf(stdin,0,_IONBF,0);setvbuf(stdout,0,_IONBF,0); #elif defined IOSTREAM ios_base::sync_with_stdio(0);cin.tie(0);cout.precision(99);cout.setf(ios::fixed,ios::floatfield); #endif #ifdef DEBUG #ifdef _WIN32 ec(0); oc(0); #else // TODO: *nix #endif #endif #ifdef READ_NUM_TEST_CASES int nz=rint;fo(i,nz) #endif tc(); #ifdef FASTIO FWRITE(_oB,1,_oP,stdout); #endif return 0; } // END OF TEMPLATE namespace ab { template<bool cond, typename T, typename F> struct IF {typedef T R;}; template<typename T, typename F> struct IF<false,T,F> {typedef F R;}; template <bool B, class T = void> struct ENABLE_IF {typedef T R;}; template <class T> struct ENABLE_IF<false, T> {}; template <bool B, class T = void> struct DISABLE_IF {typedef T RET;}; template <class T> struct DISABLE_IF<true, T> {}; template<typename A, typename B> struct SAME_TYPE { static const bool RET = false; }; template<typename T> struct SAME_TYPE<T,T> { static const bool RET = true; }; template<typename T> struct IS_CLASS { template<typename C> static char (&f(int C::*))[1]; template<typename C> static char (&f(...))[2]; static bool const R = sizeof(f<T>(0))==1; }; /* struct FALSE { static bool const R = false; };*/ template<class T> struct RR{ typedef typename std::remove_reference<T>::type R; }; // get &T::x or &T::first template<class T,class=void>struct GET_X{}; template<class T>struct GET_X<T,typename std::enable_if<std::is_object<decltype(T::x)>::value>::type>{typedef decltype(&T::x) R;}; template<class T>struct GET_X<T,typename std::enable_if<std::is_object<decltype(T::first)>::value>::type>{typedef decltype(&T::first) R;}; // get &T::y or &T::second template<class T,class=void>struct GET_Y{}; template<class T>struct GET_Y<T,typename std::enable_if<std::is_object<decltype(T::y)>::value>::type>{typedef decltype(&T::y) R;}; template<class T>struct GET_Y<T,typename std::enable_if<std::is_object<decltype(T::second)>::value>::type>{typedef decltype(&T::second) R;}; } namespace ab{ /////////////////////////////// STATIC ARRAY /////////////////////////////////// // requires: TEMPLATES // // Copyright (c) 2013 by Adam Blaszkiewicz. All rights reserved. // template<typename T, int _capacity> class StaticArray { public: StaticArray() : mSize(0) {} StaticArray(unsigned int _size) : mSize(_size) {A(_size<=_capacity);} inline void push_back(const T& t) {new(&mData()[mSize]) T(t); ++mSize;} inline void push_back() {new(&mData()[mSize]) T; ++mSize;} inline void pop_back() {A(mSize>0); --mSize; mData()[mSize].~T();} inline T& operator[](const int idx) {return mData()[idx];} inline const T& operator[](const int idx) const {A(idx<mSize); return mData()[idx];} inline T& back() {A(mSize>0); return mData()[mSize-1];} inline const T& back() const {A(mSize>0); return mData()[mSize-1];} inline T& front() {A(mSize>0); return mData()[0];} inline const T& front() const {A(mSize>0); return mData()[0];} inline int size() const {return mSize;} inline unsigned int capacity() const {return _capacity;} inline void resize(int newSize) { A(newSize <= _capacity); if(newSize > mSize) new (&mData()[mSize]) T[newSize-mSize]; else for(int i=newSize; i<mSize; ++i) mData()[i].~T(); mSize = newSize; } inline void reserve(int howMuch) const {A(howMuch <= _capacity);} inline void clear() {for(int i=0; i<mSize; ++i) mData()[i].~T(); mSize=0;} typedef T* iterator; inline iterator begin() {return mData;} inline iterator end() {return mData+mSize;} private: T* mData() {return reinterpret_cast<T*>(_mData);} char _mData[_capacity*sizeof(T)]; int mSize; }; // vector of at most n elements template<typename T, int n> struct _vector {typedef typename IF<n==0,std::vector<T>,StaticArray<T,n> >::R R;}; //////////////////////////////////////////////////////////////////////////////// } namespace ab{ //////////////////////// SPLAYER (for splay trees) ///////////////////////////// // // Implementation: Adam Blaszkiewicz (atablash.pl), 2013-2014 // /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // // Splayer provides some splay node operations template<bool evertable = false> struct Splayer { template<typename PV> static inline void updateUntilNode(PV x, const PV& superRoot) { while(x != superRoot) { A(x); x->template update<0,0>(); x = x->parent; } } template<typename SplayNode> static inline void updateUntilNull(SplayNode* x) { updateUntilNode(x,NULL); } template<typename SplayNode> static inline void splayUntilNode(SplayNode *x, const SplayNode* const superRoot, int level) { //int level = 0; //SplayNode *pc = x; //while(pc->parent != superRoot()) pc = pc->parent, ++level; int level2 = level/2; while(level2) splay(x),--level2; if(level&1) rotate(x); A(x->parent == superRoot); } template<typename SplayNode> static inline void splayUntilNode(SplayNode *x, SplayNode *superRoot) { int level = 0; SplayNode *pc = x; while(pc->parent != superRoot) pc = pc->parent, ++level; splayUntilNode(x,superRoot,level); } template<typename SplayNode> static inline void splayUntilNull(SplayNode *x, int level) { if(level==0)return; if(level==1)rotateLast(x); else { int level2 = level/2; while(--level2) splay(x); if(level&1) splay(x),rotateLast(x); else splayLast(x); } A(x->parent == NULL); } // returns previous root template<typename SplayNode> static inline SplayNode* splayUntilNull(SplayNode *x) { int level = 0; SplayNode *pc = x; while(pc->parent) pc = pc->parent, ++level; splayUntilNull(x,level); return pc; } // splay only right template<typename SplayNode> static inline void splayRUntilNull(SplayNode *x, int level) { if(level==0)return; if(level==1)rotateRLast(x); else { int level2 = level/2; while(--level2) rotateR(x->parent),rotateR(x); if(level&1) rotateR(x->parent),rotateR(x),rotateRLast(x); else rotateRLast(x->parent),rotateRLast(x); } A(x->parent == NULL); } // returns previous root template<typename SplayNode> static inline SplayNode* splayRUntilNull(SplayNode *x) { int level = 0; SplayNode *pc = x; while(pc->parent) pc = pc->parent, ++level; splayRUntilNull(x,level); // bugfix return pc; } // ROTATIONS // assumes x's parent is NOT root (its parent != NULL) template<typename SplayNode> static inline void rotateR(SplayNode* x) { A(x->parent && x->parent->parent); SplayNode *prevParent = rotateRLast(x); A(x->parent); if(x->parent->l == prevParent) x->parent->l = x; else {A(x->parent->r == prevParent); x->parent->r = x;} } // assumes x's parent is root (its parent == NULL) // return prev parent template<typename SplayNode> static inline SplayNode* rotateRLast(SplayNode* x) { A(x); A(x->parent); A(x->parent->l == x); // can rotate right SplayNode *parent = x->parent; SplayNode* xr; if(evertable && x->getSwapFlag()) { xr = x->l; x->l = x->r; if(x->l) x->l->setSwapFlag(!x->l->getSwapFlag()); if(xr) xr->setSwapFlag(!xr->getSwapFlag()); } else { xr = x->r; } parent->l = xr; //parent->subVal(x); //parent->addVal(xr); //x->subVal(xr); //x->addVal(parent); //x->updateCopy(parent); if(xr) { xr->parent = parent; parent->template update<1,0>(); // L } else parent->template update<-1,0>(); // NL x->parent = parent->parent; x->setSwapFlag(parent->getSwapFlag()); parent->setSwapFlag(false); x->r = parent; parent->parent = x; x->template update<0,1>(); return parent; } // assumes x's parent is NOT root (its parent != NULL) template<typename SplayNode> static inline void rotateL(SplayNode* x) { A(x->parent->parent); SplayNode *prevParent = rotateLLast(x); if(x->parent->l == prevParent) x->parent->l = x; else {A(x->parent->r == prevParent); x->parent->r = x;} } // assumes x's parent is root (its parent == NULL) // returns prev parent template<typename SplayNode> static inline SplayNode* rotateLLast(SplayNode* x) { A(x); A(x->parent); A(x->parent->r == x); // can rotate left SplayNode *parent = x->parent; SplayNode *xl; if(evertable && x->getSwapFlag()) { xl = x->r; x->r = x->l; if(x->r) x->r->setSwapFlag(!x->r->getSwapFlag()); if(xl) xl->setSwapFlag(!xl->getSwapFlag()); } else { xl = x->l; } parent->r = xl; //parent->subVal(x); //parent->addVal(xl); //x->subVal(xl); //x->addVal(parent); //x->updateCopy(parent); if(xl) { xl->parent = x->parent; parent->template update<0,1>(); // R } else parent->template update<0,-1>(); // NR x->parent = parent->parent; x->setSwapFlag(parent->getSwapFlag()); parent->setSwapFlag(false); x->l = parent; parent->parent = x; x->template update<1,0>(); return parent; } // assumes x's parent is NOT root (its parent != null) template<typename SplayNode> static inline void rotate(SplayNode* x) { A(x); A(x->parent); A(x->parent->parent); if(x->parent->r == x) rotateL(x); else {A(x->parent->l == x); rotateR(x);} } // assumes x's parent is root (its parent == null) template<typename SplayNode> static inline void rotateLast(SplayNode* x) { A(x); A(x->parent);A(!x->parent->parent); if(x->parent->r == x) rotateLLast(x); else {A(x->parent->l == x); rotateRLast(x);} } // assumes x's grandparent is NOT root (its parent != NULL) template<typename SplayNode> // TODO: can be optimized if splays aren't // done using rotate functions but directly static inline void splay(SplayNode *x) // zig-zig or zig-zag { A(x); A(x->parent); // x not root A(x->parent->parent); // parent not root A(x->parent->parent->parent); // there is superRoot SplayNode *p = x->parent; SplayNode *g = p->parent; if(evertable && p->getSwapFlag()) { if(p->l == x) { if(g->l == p) rotateR(x), rotateR(x); else {A(g->r == p); rotateL(p), rotateL(x);} } else { A(p->r == x); if(g->l == p) rotateR(p), rotateR(x); else {A(g->r == p); rotateL(x), rotateL(x);} } } else { if(p->l == x) { if(g->l == p) rotateR(p), rotateR(x); else {A(g->r == p); rotateR(x), rotateL(x);} } else { A(p->r == x); if(g->l == p) rotateL(x), rotateR(x); else {A(g->r == p); rotateL(p), rotateL(x);} } } } // assumes x's grandparent is root (its parent == NULL) template<typename SplayNode> static inline void splayLast(SplayNode *x) // zig-zig or zig-zag { A(x); A(x->parent); // x not root A(x->parent->parent); // parent not root SplayNode *p = x->parent; SplayNode *g = p->parent; if(evertable && p->getSwapFlag()) { if(p->l == x) { if(g->l == p) rotateR(x), rotateRLast(x); else {A(g->r == p); rotateLLast(p), rotateLLast(x);} } else { A(p->r == x); if(g->l == p) rotateRLast(p), rotateRLast(x); else {A(g->r == p); rotateL(x), rotateLLast(x);} } } else { if(p->l == x) { if(g->l == p) rotateRLast(p), rotateRLast(x); else {A(g->r == p); rotateR(x), rotateLLast(x);} } else { A(p->r == x); if(g->l == p) rotateL(x), rotateRLast(x); else {A(g->r == p); rotateLLast(p), rotateLLast(x);} } } } // debug template<typename SplayNode> static inline bool consistent(const SplayNode *pv) { // parent link if(pv->parent && pv->parent->l!=pv && pv->parent->r!=pv) return false; // left link if(pv->l && pv->l->parent!=pv) return false; // right link if(pv->r && pv->r->parent!=pv) return false; // children are the same if(pv->l && pv->l == pv->r) return false; if(pv->l && pv->l == pv->parent) return false; if(pv->r && pv->r == pv->parent) return false; return true; } }; //////////////////////////////////////////////////////////////////////////////// } namespace ab{ ////////////////////////// SPLAY NODES ///////////////////////////////////////// // // Implementation: Adam Blaszkiewicz (atablash.pl), 2013-2014 // /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // template<typename _Value, typename Derived> struct BaseSplayNode { // Only data, should be no vptr _Value keyval; Derived *parent; Derived *l; Derived *r; // Children-less initialization inline BaseSplayNode(const _Value& _keyval, Derived* _parent) : keyval(_keyval), parent(_parent), l(NULL), r(NULL) {} // Full initialization inline BaseSplayNode(const _Value& _keyval, Derived* _parent, Derived* _l, Derived* __r) : keyval(_keyval), parent(_parent), l(_l), r(__r) {} // PATH AGGREGATION // "pure virtual" update functions inline void update() {A(false);} inline void updateLR() {A(l && r);A(false);} inline void updateL() {A(l);A(false);} inline void updateR() {A(r);A(false);} inline void updateNL() {A(!l);A(false);} inline void updateNR() {A(!r);A(false);} inline void updateCopy(Derived* x) {A(false);} // copy stats from x // TODO: path aggregation for linear values - could be faster, // especially when updating ancestors of deleted node // swap flag - for evert (rerooting) inline bool getSwapFlag() const {A(false); return 0;} inline void setSwapFlag(bool) {A(false);} // TREE AGGREGATION (only linear values) // suitable for sum, not suitable for max inline void addVal(Derived* x) {A(false);} inline void subVal(Derived* x) {A(false);} }; template<typename _Value, typename Derived> struct CopyableSplayNode : public BaseSplayNode<_Value, Derived> { typedef BaseSplayNode<_Value,Derived> B;//ASE inline void operator=(const CopyableSplayNode& o) { B::keyval = o.keyval; B::parent = o.parent; B::l = o.l; B::r = o.r; if(B::l) B::l->parent = (Derived*)this; if(B::r) B::r->parent = (Derived*)this; if(B::parent->l == &o) B::parent->l = (Derived*)this; else {A(B::parent->r==&o); B::parent->r = (Derived*)this;} } inline CopyableSplayNode(const CopyableSplayNode& o) : B(o.keyval,o.parent,o.l,o.r) { if(B::l) B::l->parent = (Derived*)this; if(B::r) B::r->parent = (Derived*)this; if(B::parent->l == &o) B::parent->l = (Derived*)this; else {A(B::parent->r==&o); B::parent->r = (Derived*)this;} } inline CopyableSplayNode(const _Value& _keyval, Derived* _parent) : B(_keyval,_parent) {} }; // Default SplayNode: copyable, empty update functions // // CANNOT BE BASE! template<typename _Value> struct DefSplayNode : public CopyableSplayNode<_Value,DefSplayNode<_Value> > // tell Base that it's our base // (avoid vtable) { typedef CopyableSplayNode<_Value,DefSplayNode<_Value> > B;//ASE // Children-less initialization inline DefSplayNode(const _Value& _keyval, DefSplayNode* _parent) : CopyableSplayNode<_Value,DefSplayNode<_Value> >(_keyval,_parent) {} // empty update functions inline void update() {} inline void updateLR() {A(B::l && B::r);} inline void updateL() {A(B::l);} inline void updateR() {A(B::r);} inline void updateNL() {A(!B::l);} inline void updateNR() {A(!B::r);} inline void updateCopy(DefSplayNode* x) {} // copy stats from x }; //////////////////////////////////////////////////////////////////////////////// } namespace ab{ ///////////////////////////// SPLAY TREE /////////////////////////////////////// // // Implementation: Adam Blaszkiewicz (atablash.pl), 2013-2014 // /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // // Common SplayTree // // new + delete 2.88s // nodes on vector: 2.81s // nodes on vector + reserve: 2.76s // nodes on vector, no copy constructors 2.76s // after levels optim 2.74s (2.66??) // splays everywhere, some optimizations 3.08s // suddenly (after evert?) 3.40s // // does not support evert (swapFlag) (TODO?) template<typename _Key, typename _Value, typename _KeyOfVal, typename SplayNode = DefSplayNode<_Value>, int MaxNodes = 0, typename _Alloc = std::allocator<_Value> > class SplayTree { public: class iterator; private: typedef _Key key_type; typedef _Value value_type; typedef _Alloc allocator_type; typedef typename _Alloc::template rebind<SplayNode>::other NodeAlloc; typedef Splayer<false> SP; // not evertable! public: inline SplayTree() { superRoot()->r = NULL; superRoot()->l = NULL; superRoot()->parent = NULL; } inline ~SplayTree() { //A(!superRoot()->r); //if(superRoot()->l) _destroyNode(superRoot()->l); } private: /* void _destroyNode(SplayNode *pn) { if(pn->l) _destroyNode(pn->l); if(pn->r) _destroyNode(pn->r); nodeAlloc.destroy(pn); nodeAlloc.deallocate(pn,1); }*/ private: SplayNode* newNode(const _Value& _keyval, SplayNode* parent) { //_v.push_back(node); //return &_v.back(); return new SplayNode(_keyval, parent); } void delNode(SplayNode* sn) { //if(sn!=&_v.back()) *sn = _v.back(); //_v.pop_back(); delete sn; // TODO: zwalniac pamiec moze? (!) } public: inline iterator find(const value_type& _keyval, const bool splay = true) { tuple<SplayNode*,SplayNode**,int> re = _find(_keyval); SplayNode* pNode = get<0>(re); SplayNode** ppNode = get<1>(re); int level = get<2>(re); if(*ppNode) { if(splay) { SP::splayUntilNode(*ppNode,superRoot(),level); return iterator(superRoot()->l); } else return iterator(*ppNode); } else { if(splay && level>0) SP::splayUntilNode(pNode,superRoot(),level-1); return iterator(superRoot()); } } inline pair<iterator,bool> insert(const value_type& _keyval, const bool splay = true) { //if(_v.size()==_v.capacity())_v.reserve(_v.size()*3/2); tuple<SplayNode*,SplayNode**,int> re = _find(_KeyOfVal()(_keyval)); SplayNode* pNode = get<0>(re); SplayNode** ppNode = get<1>(re); int level = get<2>(re); if(*ppNode) { auto result = *ppNode; if(splay) SP::splayUntilNode(*ppNode,superRoot(),level); return make_pair(iterator(result),false); } else { //SplayNode nn(_keyval,pNode); *ppNode = newNode(_keyval,pNode); auto result = *ppNode; A(result); if(splay){ SP::splayUntilNode(*ppNode,superRoot(),level); result->template update<0,0>(); // TODO: may be unnecessary when there are any splays } // TODO: update when not splaying A(result); return make_pair(iterator(result),true); } } inline iterator insertMulti(const value_type& _keyval, const bool splay = true) { //if(_v.size()==_v.capacity())_v.reserve(_v.size()*3/2); pair<SplayNode*,SplayNode**> re = _findForInsert(_KeyOfVal(_keyval)); re.se = newNode(_keyval,re.fi); if(splay) splayToRoot(*re.se,re.th); return iterator(re.se); } inline void erase(const key_type& _key, const bool splay = true) { erase(find(_key,splay)); } inline void safe_erase(const key_type& _key, const bool splay = true) { iterator itr = find(_key, splay); if(itr != end()) erase(itr); } inline void erase(const iterator& itr, const bool splay = true) { A(itr != end()); _erase(itr.p, splay); } inline iterator begin() { SplayNode *pc = superRoot(); while(pc->l) pc = pc->l; return iterator(pc); } inline iterator end() { return iterator(superRoot()); } inline bool isRoot(SplayNode* x) const { return x->parent == NULL; } inline void clear() { //_v.clear(); superRoot()->l = NULL; } inline void reserve(unsigned int size) { //_v.reserve(size); } private: // assumes x has no children inline void _justErase(SplayNode* x) { A(x != superRoot()); A(!x->l); A(!x->r); if(x->parent->r == x) { x->parent->r = NULL; if(x->parent != superRoot()) { x->parent->template update<0,-1>();//NR SP::updateUntilNode(x->parent->parent,superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } else { A(x->parent->l == x); x->parent->l = NULL; if(x->parent != superRoot()) { x->parent->template update<-1,0>();//NL SP::updateUntilNode(x->parent->parent,superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } delNode(x); } // assumes x has only left child inline void _eraseL(SplayNode* x) { A(x != superRoot()); A(x->l); A(!x->r); if(x->parent->l == x) { x->parent->l = x->l; if(x->parent != superRoot()) { x->parent->template update<1,0>();//L SP::updateUntilNode(x->parent->parent,superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } else { A(x->parent->r == x); x->parent->r = x->l; if(x->parent != superRoot()) { x->parent->template update<0,1>();//R SP::updateUntilNode(x->parent->parent, superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } x->l->parent = x->parent; delNode(x); } // assumes x has only right child inline void _eraseR(SplayNode* x) { A(x != superRoot()); A(!x->l); A(x->r); if(x->parent->l == x) { x->parent->l = x->r; if(x->parent != superRoot()) { x->parent->template update<1,0>();//L SP::updateUntilNode(x->parent->parent,superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } else { A(x->parent->r == x); x->parent->r = x->r; if(x->parent != superRoot()) { x->parent->template update<0,1>();//R SP::updateUntilNode(x->parent->parent,superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } x->r->parent = x->parent; delNode(x); } // assumes x has both children // replaces x with its predecessor inline void _eraseIn(SplayNode* const x, const bool splay = true) { A(x != superRoot()); A(x->l); A(x->r); SplayNode *c = x->l; if(c->r) { c = c->r; if(splay) { int level = 0; while(c->r) c = c->r, ++level; SplayNode* p = c->parent; p->r = c->l; if(c->l) { //c->subVal(c->l); c->l->parent = p; p->template update<0,1>();//R } else p->template update<0,-1>();//NR int level2 = level/2; while(level2) { SP::rotateL(p->parent); SP::rotateL(p); --level2; } if(level&1) { SP::rotateL(p); } //p->subVal(c); //p->template updateL(c); A(p->parent == x); // splay succeeded } else // if(!splay) // TODO: fix updates { while(c->r) c = c->r; c->parent->r = c->l; if(c->l) { c->subVal(c->l); c->l->parent = c->parent; c->parent->template update<0,1>();//R } else c->parent->template update<0,-1>();//NR c->parent->subVal(c); SplayNode *cn = c->parent->parent; while(cn != x) { cn->template update<0,1>();//R cn->subVal(c); cn = cn->parent; } } c->l = x->l; c->l->parent = c; c->parent = x->parent; if(x->parent->l == x) x->parent->l = c; else {A(x->parent->r == x); x->parent->r = c;} c->r = x->r; c->r->parent = c; c->template update<1,1>();//LR //c->addVal(c->l); //c->addVal(c->r); } else { c->parent = x->parent; if(x->parent->l == x) x->parent->l = c; else {A(x->parent->r == x); x->parent->r = c;} c->r = x->r; c->r->parent = c; c->template update<0,1>();//R c->addVal(c->r); } for(;;) // TODO: replace with updateUntilNode { c = c->parent; if(c==superRoot())break; c->template update<0,0>(); //c->subVal(x); } delNode(x); } // select appriopriate erase function to call inline void _erase(SplayNode* x, const bool splay = true, int level = -1) { SplayNode* parent = x->parent; if(x->l) { if(x->r) _eraseIn(x,splay); else _eraseL(x); } else { if(x->r) _eraseR(x); else _justErase(x); } // splay parent if(splay && parent!=superRoot()) { if(level != -1) SP::splayUntilNode(parent,superRoot(),level-1); else SP::splayUntilNode(parent,superRoot()); } } public: class iterator { friend class SplayTree; public: //private: // ugly hack?! inline iterator(SplayNode *_p) : p(_p) {} public: inline bool operator==(const iterator& o) const {return p==o.p;} inline bool operator!=(const iterator& o) const {return !(*this==o);} inline value_type& operator*() {return p->keyval;} inline const value_type& operator*() const {return p->keyval;} inline value_type* operator->() {return &p->keyval;} inline const value_type* operator->() const {return &p->keyval;} inline SplayNode* getnode(){ // todo: is this an ugly hack? return p; } inline iterator& operator++() { A(p); if(p->r) { p = p->r; while(p->l) p = p->l; } else { while(p->parent->r == p) p = p->parent; p = p->parent; } return *this; } inline iterator& operator--() { A(p); if(p->l) { p = p->l; while(p->r) p = p->r; } else { while(p->parent->l == p){ p = p->parent; A(p->parent);//!=superRoot()); } p = p->parent; } return *this; } inline iterator& operator++(int) { iterator itr(*this); ++*this; return itr; } inline iterator& operator--(int) { iterator itr(*this); --*this; return itr; } private: SplayNode *p; }; public: SplayNode& root(){ A(superRoot()->l); return *superRoot()->l; } private: //typename _vector<SplayNode,MaxNodes>::R _v; // TODO: zrobic znowu! // super root is not initialized since we only use its l,r,parent pointers // it's the greatest node of the tree, has only left son char _superRoot[sizeof(SplayNode)]; inline SplayNode* superRoot() { SplayNode *sr = reinterpret_cast<SplayNode*>(_superRoot); return sr; } // finds an element and returns <node,parent's pointer to this node, depth(level)> inline tuple<SplayNode*,SplayNode**,int> _find(const key_type& _key) { int level = 0; if(superRoot()->l == 0) return make_tuple(superRoot(),&superRoot()->l,0); SplayNode *cand = superRoot()->l; for(;;) //while(_KeyOfVal()((cand)->keyval) != _key) { if(_KeyOfVal()((cand)->keyval) < _key) { ++level; if((cand)->r) cand = (cand)->r; else return make_tuple((cand),&(cand)->r,level); } else if(_key < _KeyOfVal()((cand)->keyval)) { ++level; if((cand)->l) cand = (cand)->l; else return make_tuple((cand),&(cand)->l,level); } else break; } return make_tuple((cand)->parent, cand->parent->r==cand?&cand->parent->r:&cand->parent->l,level); } // finds a place to insert a new element, possibly equal to some others already present // returns parent's pointer to this node inline SplayNode** _findForInsert(const key_type& _key) // multiset { SplayNode **cand = &superRoot()->l; while(*cand != NULL) { if(_KeyOfVal()((*cand)->keyval) <= _key) cand = &(*cand)->r; else cand = &(*cand)->l; } return cand; } }; ////////////////////////////////////////////////////// (splay tree) //////////// template<typename T, class Node = DefSplayNode<T> > class SplaySet : public SplayTree<T,T,_Identity<T>, Node>{}; } typedef pair<ll,ll> pll; struct point{ ll x,y; }; int n,m; int w,h; struct elem{ bool operator<(const elem&o)const{ return pos.y < o.pos.y; } elem() : pos(point{LLONG_MAX,LLONG_MAX}), val(0) {} elem(point p, int v) : pos(p), val(v) {} point pos; int val; }; vector<elem> elems; point tr(int x, int y){ return point{(ll)x*h - (ll)y*w, (ll)x*h + (ll)y*w}; } struct node : public CopyableSplayNode<elem,node> { typedef CopyableSplayNode<elem,node> B;//ASE // Children-less initialization node(const elem& _keyval, node* _parent) : CopyableSplayNode<elem,node>(_keyval,_parent), sum(0), sufmax(-LLONG_MAX) {} // splay aggregates ll sum; ll sufmax; node* getsufmax(){ if(r && r->sufmax == sufmax) return r->getsufmax(); if(!r && sufmax == keyval.val) return this; if(r && sufmax == r->sum + keyval.val) return this; A(l); if(r && sufmax == r->sum + keyval.val + l->sufmax)return l->getsufmax(); A(!r); A(sufmax == keyval.val + l->sufmax); return l->getsufmax(); } bool getSwapFlag()const {return false;} void setSwapFlag(bool) {} template<int L, int R> void update(){ sum=keyval.val; sufmax = -LLONG_MAX; if(L==1 || (L==0 && l)){ sum += l->sum; if(R==1 || r) sufmax = max(sufmax,l->sufmax + keyval.val + r->sum); else sufmax = max(sufmax,l->sufmax + keyval.val); } if(R==1 || (R==0 && r)){ sum += r->sum; sufmax = max(sufmax,r->sufmax); sufmax = max(sufmax,keyval.val + r->sum); } else sufmax = max(sufmax, (ll)keyval.val); } }; // todo: to powinna byŠ mapa typedef SplaySet<elem,node> SET; SET secik; inline void tc() { E<<"welcome."<<N; I>>n>>m; I>>w>>h; fo(i,n){ int x,y,z; I>>x>>y>>z; elems.pub(elem{tr(x,y),z}); } fo(i,m){ int x,y,z; I>>x>>y>>z; elems.pub(elem{tr(x,y),-z}); } E<<"sort"<<N; sort(all(elems),[](const elem&a,const elem&b){return pll(a.pos.x,-a.pos.y) < pll(b.pos.x,-b.pos.y);}); ll result = 0; fo(i,elems.sz){ E<<N<<"PROCESS "<<elems[i].val<<N; auto&e = elems[i]; auto r = secik.insert(e); A(&*r.fi); if(!r.se){ r.fi->val += e.val; r.fi.getnode()->update<0,0>(); } auto c = r.fi; E<<"inserted "<<c->val<<N; // merge right E<<"begin merging"<<N; for(;;){ if(c->val <= 0) break; auto next = c; ++next; if(next==secik.end()){ E<<"merge right reached end"<<N; A(c->val > 0); E<<"merge me hard, honey, be my -LLONG_MAX"<<N; //secik.find(*c); // splay c->pos.y = -LLONG_MAX; //c.getnode()->update<0,0>(); break; } secik.find(*next); // splay E<<next->val<<" += "<<c->val<<N; next->val += c->val; next.getnode()->update<0,0>(); secik.erase(c); c = next; } E<<"sufmax is now "<<secik.root().sufmax<<N; if(secik.root().sufmax > 0){ E<<"result += "<<secik.root().sufmax<<N; result += secik.root().sufmax; auto ee = secik.root().getsufmax(); A(ee->keyval.val >= 0); SET::iterator it(ee); int dbgnum = 0; for(;;){ auto last = secik.end(); --last; if(last == it)break; secik.erase(last); ++dbgnum; } secik.erase(it); ++dbgnum; E<<" erased "<<dbgnum<<" elements"<<N; } } O<<result<<N; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 | //#define READ_NUM_TEST_CASES //#define ASSERTS // force asserts on online judge //#define OLD_COMPILER // (SOLUTION IS AT THE END OF THIS FILE) ////////////////////////// PROTOTYPING TEMPLATE ///////////////////////////////// // // Implementation: Adam Blaszkiewicz (atablash.pl), 2012-2014 /* This program is licensed under GNU General Public License version 3. See <http://www.gnu.org/licenses/>. */ // // // enable c++ iostream; only if no fastio //#define IOSTREAM //#define NO_UNLOCKED // fread_unlocked, fwrite_unlocked #define mp make_pair #define it iterator #define be begin() #define en end() #define sz size() #define fi first #define se second #define pub push_back #define puf push_front #define pob pop_back() #define pof pop_front() #define bs binary_search #define lb lower_bound #define ub upper_bound #define fo3(i,a,b) for(int i=(int)(a); i<(int)(b); ++i) #define of3(i,a,b) for(int i=(int)((b)-1); i>=(int)(a); --i) #define fo2(i,n) fo3(i,0,n) #define of2(i,n) of3(i,0,n) #define fo(...) VA_SEL(fo,__VA_ARGS__) #define of(...) VA_SEL(of,__VA_ARGS__) #define inl inline __attribute__ ((always_inline)) #define ninl __attribute__ ((noinline)) #ifdef OLD_COMPILER #include<vector> #include<map> #include<queue> #include<algorithm> #include<string> #include<stdint.h> #include<cstring> #include<iostream> #else #include<bits/stdc++.h> #endif #ifdef OLD_COMPILER #else #include<cstdint> #endif #include<utility> namespace ab{ typedef int8_t i8; typedef uint8_t ui8; typedef int16_t i16; typedef uint16_t ui16; typedef int32_t i32; typedef uint32_t ui32; typedef int64_t i64; typedef uint64_t ui64; // old: typedef i64 ll; typedef ui64 ull; typedef std::pair<i32,i32> pii; typedef unsigned int uint; typedef unsigned short ushort; typedef unsigned char uchar; struct VOID {}; template<typename I>struct FloatFrom{typedef VOID R;}; template<>struct FloatFrom<i32>{typedef double R;}; template<>struct FloatFrom<ui32>{typedef double R;}; template<>struct FloatFrom<i64>{typedef long double R;}; template<>struct FloatFrom<ui64>{typedef long double R;}; template<>struct FloatFrom<i16>{typedef float R;}; template<>struct FloatFrom<ui16>{typedef float R;}; template<>struct FloatFrom<i8>{typedef float R;}; template<>struct FloatFrom<ui8>{typedef float R;}; template<>struct FloatFrom<float>{typedef float R;}; template<>struct FloatFrom<double>{typedef double R;}; template<>struct FloatFrom<long double>{typedef long double R;}; template<typename I>struct Double{typedef VOID R;}; template<>struct Double<i8>{typedef i16 R;}; template<>struct Double<ui8>{typedef ui16 R;}; template<>struct Double<i16>{typedef i32 R;}; template<>struct Double<ui16>{typedef ui32 R;}; template<>struct Double<i32>{typedef i64 R;}; template<>struct Double<ui32>{typedef ui64 R;}; template<>struct Double<float>{typedef float R;}; template<>struct Double<double>{typedef double R;}; template<>struct Double<long double>{typedef long double R;}; #if defined __GNUC__ and ( __WORDSIZE == 64 ) typedef int128_t i128; typedef uint128_t ui128; template<>struct Double<i64>{typedef i128 R;}; template<>struct Double<ui64>{typedef ui128 R;}; #endif } #define FASTIO #ifdef NO_FASTIO #undef FASTIO #endif #ifdef DEBUG #undef NDEBUG #pragma message "Compiling in DEBUG mode." #undef FASTIO #ifdef _WIN32 #include<windows.h> inline void ec(int a){static HANDLE h=GetStdHandle(-12);SetConsoleTextAttribute(h,a?12:0xf);} inline void oc(int a){static HANDLE h=GetStdHandle(-11);SetConsoleTextAttribute(h,a?10:0xf);} #else // *nix includes for debug #endif #else #define NDEBUG #define ec(x) #define oc(x) #endif #include <cstdio> #include <cfloat> #ifdef OLD_COMPILER // TODO #else #include<type_traits> #endif #define _CAT(a,b) a##b #define CAT(a,b) _CAT(a,b) #define _10TH(a,b,c,d,e,f,g,h,i,CNT,...) CNT #define VA_CNT(...) _10TH(__VA_ARGS__,9,8,7,6,5,4,3,2,1) #define VA_SEL(a,...) CAT(a,VA_CNT(__VA_ARGS__))(__VA_ARGS__) #define _VA_GTONE(...) _10TH(__VA_ARGS__,1,1,1,1,1,1,1,1,0) #define VA_GTONE(a,...) CAT(a,_VA_GTONE(__VA_ARGS__))(__VA_ARGS__) #define foreach(e,c) for(__typeof((c).begin())e=(c).begin();e!=(c).end();++e) #define MIN_GCC(a,b,c) (__GNUC__ > (a) || \ (__GNUC__ == (a) && (__GNUC_MINOR__ > (b) || \ (__GNUC_MINOR__ == (b) && \ __GNUC_PATCHLEVEL__ >= (c))))) #define L0(str) fprintf(stderr,"%s:%d - " str "\n",__FILE__,__LINE__) #define L1(str,...) fprintf(stderr,"%s:%d - " str "\n",__FILE__,__LINE__,__VA_ARGS__) #define L(...) VA_GTONE(L,__VA_ARGS__) #ifdef NDEBUG #define D if(0) #define A(x) #define TEST_FLOAT(x) #define ASSERT_FLOAT(x) #else #define A(x) assert(x); #define _TEST_FLOAT(x) ((x) <= LDBL_MAX && (x) >= -LDBL_MAX) #define ASSERT_FLOAT(f) A(_TEST_FLOAT(f)) #define D #endif #define V(x) (E<<#x<<": "<<(x)<<N) #define XX {E<<"XX LINE "<<__LINE__<<N;} #if defined DEBUG or defined ASSERTS #undef NDEBUG #else #define NDEBUG #endif #ifdef _WIN32 // TODO #ifndef NO_UNLOCKED #define NO_UNLOCKED #endif //#define fread_unlocked _fread_nolock //#define fwrite_unlocked _fwrite_nolock #endif #define all(x) (x).be,(x).en #define type(x) __typeof(x) const char N='\n'; const char S=' '; using namespace std; using namespace __gnu_cxx; namespace ab{} using namespace ab; template<class T>inline T cbitl(T x,int i){return (x<<i) ^ (x>>(sizeof(T)*8-i));} namespace std{ #if defined __GNUC__ and not MIN_GCC(4,2,0) template<class T>struct hash<T>{} #endif // 1,2,last (!!!!!) template<>template<class A,class B>struct hash<map<A,B>>{ size_t operator()(const map<A,B>& m) const{ size_t r = m.size(); if(!r)return r; auto i=m.be; r^=hash<type(i)>()(i); ++i; r^=cbitl(hash<type(i)>()(*i),sizeof(r)*8/4); i=m.end(); --i; r^=cbitl(hash<type(i)>()(*i),sizeof(r)*8/2); return r; } }; template<>template<class A, class B>struct hash<pair<A,B>>{ size_t operator()(const pair<A,B>& p) const{ return hash<A>()(p.first) ^ cbitl(hash<B>()(p.second),sizeof(size_t)*8/2); } }; } #define rint _rint() #define ruint _ruint() #define rll _rll() #define rull _rull() #define rchar _rchar() #ifndef FASTIO inline void fin(int){}inline void fout(int){} #ifdef IOSTREAM inline int _rint(){int r;cin>>r;return r;} inline uint _ruint(){uint r;cin>>r;return r;} inline ull _rull(){ull r;cin>>r;return r;} inline char _rchar(){return cin.get();} template<typename T>inline void W(const T& i){cout<<i;} inline void W(){W('\n');} #else inline int _rint(){int r;scanf("%d",&r);return r;} inline uint _ruint(){uint r;scanf("%u",&r);return r;} inline ull _rull(){ull r;scanf("%llu",&r);return r;} inline ull _rll(){ll r;scanf("%lld",&r);return r;} inline char _rchar(){return getchar();} inline void W(char a='\n'){printf("%c",a);} inline void W(int a){printf("%d",a);} inline void W(uint a){printf("%u",a);} inline void W(const ull& a){printf("%llu",a);} inline void W(const ll& a){printf("%lld",a);} inline void W(const char *str){fputs(str,stdout);} inline void W(const double& d){printf("%.20f",d);} inline void W(const long double& d){printf("%.50Lf",d);} #endif #else #ifndef NO_UNLOCKED #define FREAD fread_unlocked #define FWRITE fwrite_unlocked #else #define FREAD fread #define FWRITE fwrite #endif // todo: test on pointers const int _IB=32768;const int _OB=32768; char _iB[_IB];int _iP = _IB;char _oB[_OB];int _oP = 0; inline void fin(int mc){int r=_IB-_iP;if(r>mc)return;fo(i,r)_iB[i]=_iB[i+_iP]; // TODO: memcpy FREAD(_iB+r,1,_iP,stdin);_iP = 0;} inline void fout(int mc){if(_OB-_oP>mc)return;FWRITE(_oB,1,_oP,stdout);_oP = 0;} inline void W(char c='\n'){_oB[_oP++]=c;} inline char _rchar(){return _iB[_iP++];} template<class T>inline T _rur(){ T r=0;char c=rchar; do c-='0',r=r*10+c,c=rchar;while(c>='0'); return r;} template<class T>inline T _rsi(){ char c=rchar; while(c<'-')c=rchar; if(c=='-')return -_rur<T>(); else{--_iP;return _rur<T>();}} template<class T>inline T _ru(){while(rchar<'0');--_iP;return _rur<T>();} inline int _rint(){fin(15);return _rsi<int>();} inline uint _ruint(){fin(15);return _ru<uint>();} inline ll _rll(){fin(25);return _rsi<ll>();} inline ull _rull(){fin(25);return _ru<ull>();} const int _rs = 20;char _r[_rs]; template<class T>inline void _w(T i){ if(numeric_limits<T>::is_signed && i<0)W('-'),i=-i; else if(i==0){W('0');return;} int pos = _rs; do{_r[--pos]='0'+i%10;i/=10;}while(i); do W(_r[pos]),++pos;while(pos<_rs);} inline void W(const int32_t& i){fout(15);_w(i);} inline void W(const uint32_t& i){fout(15);_w(i);} inline void W(const int64_t& i){fout(25);_w(i);} inline void W(const uint64_t& i){fout(25);_w(i);} inline void W(const char*str){int l=strlen(str);fout(l);memcpy(&_oB[_oP],str,l);_oP+=l;} inline void W(double d){fout(50);_oP+=sprintf(&_oB[_oP],"%.20f",d);} // todo #endif template<class A,class B>inline void W(const A&a,const B&b){W(a);W(b);} template<class A,class B,class C> inline void W(const A&a,const B&b,const C&c){W(a);W(b);W(c);} template<class A,class B,class C,class DD> inline void W(const A&a,const B&b,const C&c,const DD&dd){W(a);W(b);W(c);W(dd);} template<class T>inline void sortall(T&t){sort(t.be,t.en);} template<class T>inline void uniqall(T&t){t.resize(unique(t.be,t.en)-t.be);} inline int count1(uint i){return __builtin_popcount(i);} inline int count1(ull i){return __builtin_popcountll(i);} inline int parity(uint i){return __builtin_parity(i);} inline int parity(ull i){return __builtin_parityll(i);} inline int ilog(uint i){return 31-__builtin_clz(i);} // int log; floor(log2(i)) inline int ilog(ull i){return 63-__builtin_clzll(i);} #define powerof2(x) !(x&(x-1)) #define subset(a,b) (a&b==a) #define kbegin(k) ((1<<k)-1) #define kend(k,n) ((kbegin(k)<<n-k)+1) inline uint knext(uint a){uint b=(a|(a-1))+1;return b|((a^b)>>(__builtin_ctz(a)+2));} #define fors(x,k,n) for(uint x=kbegin(k);x<kend(k,n);x=knext(x)) template<class A,class B>inline ostream&operator<<(ostream&o,const pair<A,B>&p){o<<'<'<<p.fi<<", "<<p.se<<'>';return o;} template<class A,class B>inline ostream&operator<<(ostream&o,const map<A,B>&m){o<<N;for(auto&k:m)o<<"map["<<k.fi<<"] -> "<<k.se<<N;return o;} template<class A>inline ostream&operator<<(ostream&o,const vector<A>&_v){o<<N;fo(i,_v.sz)o<<"vector["<<i<<"] = "<<_v[i]<<N;return o;} struct _O{template<class T>_O&operator<<(const T&t){oc(1);W(t);oc(0);return*this;}}O; struct _I{ _I&operator>>(int32_t&t){t=rint;return*this;} _I&operator>>(uint32_t&t){t=ruint;return*this;} _I&operator>>(int64_t&t){t=rll;return*this;} _I&operator>>(uint64_t&t){t=rull;return*this;} }I; struct _E{template<class T>_E&operator<<(const T&t){D{ec(1);cerr<<t;ec(0);}return*this;}}E; inline void tc(); int main() { #ifdef FASTIO setvbuf(stdin,0,_IONBF,0);setvbuf(stdout,0,_IONBF,0); #elif defined IOSTREAM ios_base::sync_with_stdio(0);cin.tie(0);cout.precision(99);cout.setf(ios::fixed,ios::floatfield); #endif #ifdef DEBUG #ifdef _WIN32 ec(0); oc(0); #else // TODO: *nix #endif #endif #ifdef READ_NUM_TEST_CASES int nz=rint;fo(i,nz) #endif tc(); #ifdef FASTIO FWRITE(_oB,1,_oP,stdout); #endif return 0; } // END OF TEMPLATE namespace ab { template<bool cond, typename T, typename F> struct IF {typedef T R;}; template<typename T, typename F> struct IF<false,T,F> {typedef F R;}; template <bool B, class T = void> struct ENABLE_IF {typedef T R;}; template <class T> struct ENABLE_IF<false, T> {}; template <bool B, class T = void> struct DISABLE_IF {typedef T RET;}; template <class T> struct DISABLE_IF<true, T> {}; template<typename A, typename B> struct SAME_TYPE { static const bool RET = false; }; template<typename T> struct SAME_TYPE<T,T> { static const bool RET = true; }; template<typename T> struct IS_CLASS { template<typename C> static char (&f(int C::*))[1]; template<typename C> static char (&f(...))[2]; static bool const R = sizeof(f<T>(0))==1; }; /* struct FALSE { static bool const R = false; };*/ template<class T> struct RR{ typedef typename std::remove_reference<T>::type R; }; // get &T::x or &T::first template<class T,class=void>struct GET_X{}; template<class T>struct GET_X<T,typename std::enable_if<std::is_object<decltype(T::x)>::value>::type>{typedef decltype(&T::x) R;}; template<class T>struct GET_X<T,typename std::enable_if<std::is_object<decltype(T::first)>::value>::type>{typedef decltype(&T::first) R;}; // get &T::y or &T::second template<class T,class=void>struct GET_Y{}; template<class T>struct GET_Y<T,typename std::enable_if<std::is_object<decltype(T::y)>::value>::type>{typedef decltype(&T::y) R;}; template<class T>struct GET_Y<T,typename std::enable_if<std::is_object<decltype(T::second)>::value>::type>{typedef decltype(&T::second) R;}; } namespace ab{ /////////////////////////////// STATIC ARRAY /////////////////////////////////// // requires: TEMPLATES // // Copyright (c) 2013 by Adam Blaszkiewicz. All rights reserved. // template<typename T, int _capacity> class StaticArray { public: StaticArray() : mSize(0) {} StaticArray(unsigned int _size) : mSize(_size) {A(_size<=_capacity);} inline void push_back(const T& t) {new(&mData()[mSize]) T(t); ++mSize;} inline void push_back() {new(&mData()[mSize]) T; ++mSize;} inline void pop_back() {A(mSize>0); --mSize; mData()[mSize].~T();} inline T& operator[](const int idx) {return mData()[idx];} inline const T& operator[](const int idx) const {A(idx<mSize); return mData()[idx];} inline T& back() {A(mSize>0); return mData()[mSize-1];} inline const T& back() const {A(mSize>0); return mData()[mSize-1];} inline T& front() {A(mSize>0); return mData()[0];} inline const T& front() const {A(mSize>0); return mData()[0];} inline int size() const {return mSize;} inline unsigned int capacity() const {return _capacity;} inline void resize(int newSize) { A(newSize <= _capacity); if(newSize > mSize) new (&mData()[mSize]) T[newSize-mSize]; else for(int i=newSize; i<mSize; ++i) mData()[i].~T(); mSize = newSize; } inline void reserve(int howMuch) const {A(howMuch <= _capacity);} inline void clear() {for(int i=0; i<mSize; ++i) mData()[i].~T(); mSize=0;} typedef T* iterator; inline iterator begin() {return mData;} inline iterator end() {return mData+mSize;} private: T* mData() {return reinterpret_cast<T*>(_mData);} char _mData[_capacity*sizeof(T)]; int mSize; }; // vector of at most n elements template<typename T, int n> struct _vector {typedef typename IF<n==0,std::vector<T>,StaticArray<T,n> >::R R;}; //////////////////////////////////////////////////////////////////////////////// } namespace ab{ //////////////////////// SPLAYER (for splay trees) ///////////////////////////// // // Implementation: Adam Blaszkiewicz (atablash.pl), 2013-2014 // /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // // Splayer provides some splay node operations template<bool evertable = false> struct Splayer { template<typename PV> static inline void updateUntilNode(PV x, const PV& superRoot) { while(x != superRoot) { A(x); x->template update<0,0>(); x = x->parent; } } template<typename SplayNode> static inline void updateUntilNull(SplayNode* x) { updateUntilNode(x,NULL); } template<typename SplayNode> static inline void splayUntilNode(SplayNode *x, const SplayNode* const superRoot, int level) { //int level = 0; //SplayNode *pc = x; //while(pc->parent != superRoot()) pc = pc->parent, ++level; int level2 = level/2; while(level2) splay(x),--level2; if(level&1) rotate(x); A(x->parent == superRoot); } template<typename SplayNode> static inline void splayUntilNode(SplayNode *x, SplayNode *superRoot) { int level = 0; SplayNode *pc = x; while(pc->parent != superRoot) pc = pc->parent, ++level; splayUntilNode(x,superRoot,level); } template<typename SplayNode> static inline void splayUntilNull(SplayNode *x, int level) { if(level==0)return; if(level==1)rotateLast(x); else { int level2 = level/2; while(--level2) splay(x); if(level&1) splay(x),rotateLast(x); else splayLast(x); } A(x->parent == NULL); } // returns previous root template<typename SplayNode> static inline SplayNode* splayUntilNull(SplayNode *x) { int level = 0; SplayNode *pc = x; while(pc->parent) pc = pc->parent, ++level; splayUntilNull(x,level); return pc; } // splay only right template<typename SplayNode> static inline void splayRUntilNull(SplayNode *x, int level) { if(level==0)return; if(level==1)rotateRLast(x); else { int level2 = level/2; while(--level2) rotateR(x->parent),rotateR(x); if(level&1) rotateR(x->parent),rotateR(x),rotateRLast(x); else rotateRLast(x->parent),rotateRLast(x); } A(x->parent == NULL); } // returns previous root template<typename SplayNode> static inline SplayNode* splayRUntilNull(SplayNode *x) { int level = 0; SplayNode *pc = x; while(pc->parent) pc = pc->parent, ++level; splayRUntilNull(x,level); // bugfix return pc; } // ROTATIONS // assumes x's parent is NOT root (its parent != NULL) template<typename SplayNode> static inline void rotateR(SplayNode* x) { A(x->parent && x->parent->parent); SplayNode *prevParent = rotateRLast(x); A(x->parent); if(x->parent->l == prevParent) x->parent->l = x; else {A(x->parent->r == prevParent); x->parent->r = x;} } // assumes x's parent is root (its parent == NULL) // return prev parent template<typename SplayNode> static inline SplayNode* rotateRLast(SplayNode* x) { A(x); A(x->parent); A(x->parent->l == x); // can rotate right SplayNode *parent = x->parent; SplayNode* xr; if(evertable && x->getSwapFlag()) { xr = x->l; x->l = x->r; if(x->l) x->l->setSwapFlag(!x->l->getSwapFlag()); if(xr) xr->setSwapFlag(!xr->getSwapFlag()); } else { xr = x->r; } parent->l = xr; //parent->subVal(x); //parent->addVal(xr); //x->subVal(xr); //x->addVal(parent); //x->updateCopy(parent); if(xr) { xr->parent = parent; parent->template update<1,0>(); // L } else parent->template update<-1,0>(); // NL x->parent = parent->parent; x->setSwapFlag(parent->getSwapFlag()); parent->setSwapFlag(false); x->r = parent; parent->parent = x; x->template update<0,1>(); return parent; } // assumes x's parent is NOT root (its parent != NULL) template<typename SplayNode> static inline void rotateL(SplayNode* x) { A(x->parent->parent); SplayNode *prevParent = rotateLLast(x); if(x->parent->l == prevParent) x->parent->l = x; else {A(x->parent->r == prevParent); x->parent->r = x;} } // assumes x's parent is root (its parent == NULL) // returns prev parent template<typename SplayNode> static inline SplayNode* rotateLLast(SplayNode* x) { A(x); A(x->parent); A(x->parent->r == x); // can rotate left SplayNode *parent = x->parent; SplayNode *xl; if(evertable && x->getSwapFlag()) { xl = x->r; x->r = x->l; if(x->r) x->r->setSwapFlag(!x->r->getSwapFlag()); if(xl) xl->setSwapFlag(!xl->getSwapFlag()); } else { xl = x->l; } parent->r = xl; //parent->subVal(x); //parent->addVal(xl); //x->subVal(xl); //x->addVal(parent); //x->updateCopy(parent); if(xl) { xl->parent = x->parent; parent->template update<0,1>(); // R } else parent->template update<0,-1>(); // NR x->parent = parent->parent; x->setSwapFlag(parent->getSwapFlag()); parent->setSwapFlag(false); x->l = parent; parent->parent = x; x->template update<1,0>(); return parent; } // assumes x's parent is NOT root (its parent != null) template<typename SplayNode> static inline void rotate(SplayNode* x) { A(x); A(x->parent); A(x->parent->parent); if(x->parent->r == x) rotateL(x); else {A(x->parent->l == x); rotateR(x);} } // assumes x's parent is root (its parent == null) template<typename SplayNode> static inline void rotateLast(SplayNode* x) { A(x); A(x->parent);A(!x->parent->parent); if(x->parent->r == x) rotateLLast(x); else {A(x->parent->l == x); rotateRLast(x);} } // assumes x's grandparent is NOT root (its parent != NULL) template<typename SplayNode> // TODO: can be optimized if splays aren't // done using rotate functions but directly static inline void splay(SplayNode *x) // zig-zig or zig-zag { A(x); A(x->parent); // x not root A(x->parent->parent); // parent not root A(x->parent->parent->parent); // there is superRoot SplayNode *p = x->parent; SplayNode *g = p->parent; if(evertable && p->getSwapFlag()) { if(p->l == x) { if(g->l == p) rotateR(x), rotateR(x); else {A(g->r == p); rotateL(p), rotateL(x);} } else { A(p->r == x); if(g->l == p) rotateR(p), rotateR(x); else {A(g->r == p); rotateL(x), rotateL(x);} } } else { if(p->l == x) { if(g->l == p) rotateR(p), rotateR(x); else {A(g->r == p); rotateR(x), rotateL(x);} } else { A(p->r == x); if(g->l == p) rotateL(x), rotateR(x); else {A(g->r == p); rotateL(p), rotateL(x);} } } } // assumes x's grandparent is root (its parent == NULL) template<typename SplayNode> static inline void splayLast(SplayNode *x) // zig-zig or zig-zag { A(x); A(x->parent); // x not root A(x->parent->parent); // parent not root SplayNode *p = x->parent; SplayNode *g = p->parent; if(evertable && p->getSwapFlag()) { if(p->l == x) { if(g->l == p) rotateR(x), rotateRLast(x); else {A(g->r == p); rotateLLast(p), rotateLLast(x);} } else { A(p->r == x); if(g->l == p) rotateRLast(p), rotateRLast(x); else {A(g->r == p); rotateL(x), rotateLLast(x);} } } else { if(p->l == x) { if(g->l == p) rotateRLast(p), rotateRLast(x); else {A(g->r == p); rotateR(x), rotateLLast(x);} } else { A(p->r == x); if(g->l == p) rotateL(x), rotateRLast(x); else {A(g->r == p); rotateLLast(p), rotateLLast(x);} } } } // debug template<typename SplayNode> static inline bool consistent(const SplayNode *pv) { // parent link if(pv->parent && pv->parent->l!=pv && pv->parent->r!=pv) return false; // left link if(pv->l && pv->l->parent!=pv) return false; // right link if(pv->r && pv->r->parent!=pv) return false; // children are the same if(pv->l && pv->l == pv->r) return false; if(pv->l && pv->l == pv->parent) return false; if(pv->r && pv->r == pv->parent) return false; return true; } }; //////////////////////////////////////////////////////////////////////////////// } namespace ab{ ////////////////////////// SPLAY NODES ///////////////////////////////////////// // // Implementation: Adam Blaszkiewicz (atablash.pl), 2013-2014 // /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // template<typename _Value, typename Derived> struct BaseSplayNode { // Only data, should be no vptr _Value keyval; Derived *parent; Derived *l; Derived *r; // Children-less initialization inline BaseSplayNode(const _Value& _keyval, Derived* _parent) : keyval(_keyval), parent(_parent), l(NULL), r(NULL) {} // Full initialization inline BaseSplayNode(const _Value& _keyval, Derived* _parent, Derived* _l, Derived* __r) : keyval(_keyval), parent(_parent), l(_l), r(__r) {} // PATH AGGREGATION // "pure virtual" update functions inline void update() {A(false);} inline void updateLR() {A(l && r);A(false);} inline void updateL() {A(l);A(false);} inline void updateR() {A(r);A(false);} inline void updateNL() {A(!l);A(false);} inline void updateNR() {A(!r);A(false);} inline void updateCopy(Derived* x) {A(false);} // copy stats from x // TODO: path aggregation for linear values - could be faster, // especially when updating ancestors of deleted node // swap flag - for evert (rerooting) inline bool getSwapFlag() const {A(false); return 0;} inline void setSwapFlag(bool) {A(false);} // TREE AGGREGATION (only linear values) // suitable for sum, not suitable for max inline void addVal(Derived* x) {A(false);} inline void subVal(Derived* x) {A(false);} }; template<typename _Value, typename Derived> struct CopyableSplayNode : public BaseSplayNode<_Value, Derived> { typedef BaseSplayNode<_Value,Derived> B;//ASE inline void operator=(const CopyableSplayNode& o) { B::keyval = o.keyval; B::parent = o.parent; B::l = o.l; B::r = o.r; if(B::l) B::l->parent = (Derived*)this; if(B::r) B::r->parent = (Derived*)this; if(B::parent->l == &o) B::parent->l = (Derived*)this; else {A(B::parent->r==&o); B::parent->r = (Derived*)this;} } inline CopyableSplayNode(const CopyableSplayNode& o) : B(o.keyval,o.parent,o.l,o.r) { if(B::l) B::l->parent = (Derived*)this; if(B::r) B::r->parent = (Derived*)this; if(B::parent->l == &o) B::parent->l = (Derived*)this; else {A(B::parent->r==&o); B::parent->r = (Derived*)this;} } inline CopyableSplayNode(const _Value& _keyval, Derived* _parent) : B(_keyval,_parent) {} }; // Default SplayNode: copyable, empty update functions // // CANNOT BE BASE! template<typename _Value> struct DefSplayNode : public CopyableSplayNode<_Value,DefSplayNode<_Value> > // tell Base that it's our base // (avoid vtable) { typedef CopyableSplayNode<_Value,DefSplayNode<_Value> > B;//ASE // Children-less initialization inline DefSplayNode(const _Value& _keyval, DefSplayNode* _parent) : CopyableSplayNode<_Value,DefSplayNode<_Value> >(_keyval,_parent) {} // empty update functions inline void update() {} inline void updateLR() {A(B::l && B::r);} inline void updateL() {A(B::l);} inline void updateR() {A(B::r);} inline void updateNL() {A(!B::l);} inline void updateNR() {A(!B::r);} inline void updateCopy(DefSplayNode* x) {} // copy stats from x }; //////////////////////////////////////////////////////////////////////////////// } namespace ab{ ///////////////////////////// SPLAY TREE /////////////////////////////////////// // // Implementation: Adam Blaszkiewicz (atablash.pl), 2013-2014 // /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // // Common SplayTree // // new + delete 2.88s // nodes on vector: 2.81s // nodes on vector + reserve: 2.76s // nodes on vector, no copy constructors 2.76s // after levels optim 2.74s (2.66??) // splays everywhere, some optimizations 3.08s // suddenly (after evert?) 3.40s // // does not support evert (swapFlag) (TODO?) template<typename _Key, typename _Value, typename _KeyOfVal, typename SplayNode = DefSplayNode<_Value>, int MaxNodes = 0, typename _Alloc = std::allocator<_Value> > class SplayTree { public: class iterator; private: typedef _Key key_type; typedef _Value value_type; typedef _Alloc allocator_type; typedef typename _Alloc::template rebind<SplayNode>::other NodeAlloc; typedef Splayer<false> SP; // not evertable! public: inline SplayTree() { superRoot()->r = NULL; superRoot()->l = NULL; superRoot()->parent = NULL; } inline ~SplayTree() { //A(!superRoot()->r); //if(superRoot()->l) _destroyNode(superRoot()->l); } private: /* void _destroyNode(SplayNode *pn) { if(pn->l) _destroyNode(pn->l); if(pn->r) _destroyNode(pn->r); nodeAlloc.destroy(pn); nodeAlloc.deallocate(pn,1); }*/ private: SplayNode* newNode(const _Value& _keyval, SplayNode* parent) { //_v.push_back(node); //return &_v.back(); return new SplayNode(_keyval, parent); } void delNode(SplayNode* sn) { //if(sn!=&_v.back()) *sn = _v.back(); //_v.pop_back(); delete sn; // TODO: zwalniac pamiec moze? (!) } public: inline iterator find(const value_type& _keyval, const bool splay = true) { tuple<SplayNode*,SplayNode**,int> re = _find(_keyval); SplayNode* pNode = get<0>(re); SplayNode** ppNode = get<1>(re); int level = get<2>(re); if(*ppNode) { if(splay) { SP::splayUntilNode(*ppNode,superRoot(),level); return iterator(superRoot()->l); } else return iterator(*ppNode); } else { if(splay && level>0) SP::splayUntilNode(pNode,superRoot(),level-1); return iterator(superRoot()); } } inline pair<iterator,bool> insert(const value_type& _keyval, const bool splay = true) { //if(_v.size()==_v.capacity())_v.reserve(_v.size()*3/2); tuple<SplayNode*,SplayNode**,int> re = _find(_KeyOfVal()(_keyval)); SplayNode* pNode = get<0>(re); SplayNode** ppNode = get<1>(re); int level = get<2>(re); if(*ppNode) { auto result = *ppNode; if(splay) SP::splayUntilNode(*ppNode,superRoot(),level); return make_pair(iterator(result),false); } else { //SplayNode nn(_keyval,pNode); *ppNode = newNode(_keyval,pNode); auto result = *ppNode; A(result); if(splay){ SP::splayUntilNode(*ppNode,superRoot(),level); result->template update<0,0>(); // TODO: may be unnecessary when there are any splays } // TODO: update when not splaying A(result); return make_pair(iterator(result),true); } } inline iterator insertMulti(const value_type& _keyval, const bool splay = true) { //if(_v.size()==_v.capacity())_v.reserve(_v.size()*3/2); pair<SplayNode*,SplayNode**> re = _findForInsert(_KeyOfVal(_keyval)); re.se = newNode(_keyval,re.fi); if(splay) splayToRoot(*re.se,re.th); return iterator(re.se); } inline void erase(const key_type& _key, const bool splay = true) { erase(find(_key,splay)); } inline void safe_erase(const key_type& _key, const bool splay = true) { iterator itr = find(_key, splay); if(itr != end()) erase(itr); } inline void erase(const iterator& itr, const bool splay = true) { A(itr != end()); _erase(itr.p, splay); } inline iterator begin() { SplayNode *pc = superRoot(); while(pc->l) pc = pc->l; return iterator(pc); } inline iterator end() { return iterator(superRoot()); } inline bool isRoot(SplayNode* x) const { return x->parent == NULL; } inline void clear() { //_v.clear(); superRoot()->l = NULL; } inline void reserve(unsigned int size) { //_v.reserve(size); } private: // assumes x has no children inline void _justErase(SplayNode* x) { A(x != superRoot()); A(!x->l); A(!x->r); if(x->parent->r == x) { x->parent->r = NULL; if(x->parent != superRoot()) { x->parent->template update<0,-1>();//NR SP::updateUntilNode(x->parent->parent,superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } else { A(x->parent->l == x); x->parent->l = NULL; if(x->parent != superRoot()) { x->parent->template update<-1,0>();//NL SP::updateUntilNode(x->parent->parent,superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } delNode(x); } // assumes x has only left child inline void _eraseL(SplayNode* x) { A(x != superRoot()); A(x->l); A(!x->r); if(x->parent->l == x) { x->parent->l = x->l; if(x->parent != superRoot()) { x->parent->template update<1,0>();//L SP::updateUntilNode(x->parent->parent,superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } else { A(x->parent->r == x); x->parent->r = x->l; if(x->parent != superRoot()) { x->parent->template update<0,1>();//R SP::updateUntilNode(x->parent->parent, superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } x->l->parent = x->parent; delNode(x); } // assumes x has only right child inline void _eraseR(SplayNode* x) { A(x != superRoot()); A(!x->l); A(x->r); if(x->parent->l == x) { x->parent->l = x->r; if(x->parent != superRoot()) { x->parent->template update<1,0>();//L SP::updateUntilNode(x->parent->parent,superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } else { A(x->parent->r == x); x->parent->r = x->r; if(x->parent != superRoot()) { x->parent->template update<0,1>();//R SP::updateUntilNode(x->parent->parent,superRoot()); //SP::subUntilNode(x->parent,x,superRoot()); } } x->r->parent = x->parent; delNode(x); } // assumes x has both children // replaces x with its predecessor inline void _eraseIn(SplayNode* const x, const bool splay = true) { A(x != superRoot()); A(x->l); A(x->r); SplayNode *c = x->l; if(c->r) { c = c->r; if(splay) { int level = 0; while(c->r) c = c->r, ++level; SplayNode* p = c->parent; p->r = c->l; if(c->l) { //c->subVal(c->l); c->l->parent = p; p->template update<0,1>();//R } else p->template update<0,-1>();//NR int level2 = level/2; while(level2) { SP::rotateL(p->parent); SP::rotateL(p); --level2; } if(level&1) { SP::rotateL(p); } //p->subVal(c); //p->template updateL(c); A(p->parent == x); // splay succeeded } else // if(!splay) // TODO: fix updates { while(c->r) c = c->r; c->parent->r = c->l; if(c->l) { c->subVal(c->l); c->l->parent = c->parent; c->parent->template update<0,1>();//R } else c->parent->template update<0,-1>();//NR c->parent->subVal(c); SplayNode *cn = c->parent->parent; while(cn != x) { cn->template update<0,1>();//R cn->subVal(c); cn = cn->parent; } } c->l = x->l; c->l->parent = c; c->parent = x->parent; if(x->parent->l == x) x->parent->l = c; else {A(x->parent->r == x); x->parent->r = c;} c->r = x->r; c->r->parent = c; c->template update<1,1>();//LR //c->addVal(c->l); //c->addVal(c->r); } else { c->parent = x->parent; if(x->parent->l == x) x->parent->l = c; else {A(x->parent->r == x); x->parent->r = c;} c->r = x->r; c->r->parent = c; c->template update<0,1>();//R c->addVal(c->r); } for(;;) // TODO: replace with updateUntilNode { c = c->parent; if(c==superRoot())break; c->template update<0,0>(); //c->subVal(x); } delNode(x); } // select appriopriate erase function to call inline void _erase(SplayNode* x, const bool splay = true, int level = -1) { SplayNode* parent = x->parent; if(x->l) { if(x->r) _eraseIn(x,splay); else _eraseL(x); } else { if(x->r) _eraseR(x); else _justErase(x); } // splay parent if(splay && parent!=superRoot()) { if(level != -1) SP::splayUntilNode(parent,superRoot(),level-1); else SP::splayUntilNode(parent,superRoot()); } } public: class iterator { friend class SplayTree; public: //private: // ugly hack?! inline iterator(SplayNode *_p) : p(_p) {} public: inline bool operator==(const iterator& o) const {return p==o.p;} inline bool operator!=(const iterator& o) const {return !(*this==o);} inline value_type& operator*() {return p->keyval;} inline const value_type& operator*() const {return p->keyval;} inline value_type* operator->() {return &p->keyval;} inline const value_type* operator->() const {return &p->keyval;} inline SplayNode* getnode(){ // todo: is this an ugly hack? return p; } inline iterator& operator++() { A(p); if(p->r) { p = p->r; while(p->l) p = p->l; } else { while(p->parent->r == p) p = p->parent; p = p->parent; } return *this; } inline iterator& operator--() { A(p); if(p->l) { p = p->l; while(p->r) p = p->r; } else { while(p->parent->l == p){ p = p->parent; A(p->parent);//!=superRoot()); } p = p->parent; } return *this; } inline iterator& operator++(int) { iterator itr(*this); ++*this; return itr; } inline iterator& operator--(int) { iterator itr(*this); --*this; return itr; } private: SplayNode *p; }; public: SplayNode& root(){ A(superRoot()->l); return *superRoot()->l; } private: //typename _vector<SplayNode,MaxNodes>::R _v; // TODO: zrobic znowu! // super root is not initialized since we only use its l,r,parent pointers // it's the greatest node of the tree, has only left son char _superRoot[sizeof(SplayNode)]; inline SplayNode* superRoot() { SplayNode *sr = reinterpret_cast<SplayNode*>(_superRoot); return sr; } // finds an element and returns <node,parent's pointer to this node, depth(level)> inline tuple<SplayNode*,SplayNode**,int> _find(const key_type& _key) { int level = 0; if(superRoot()->l == 0) return make_tuple(superRoot(),&superRoot()->l,0); SplayNode *cand = superRoot()->l; for(;;) //while(_KeyOfVal()((cand)->keyval) != _key) { if(_KeyOfVal()((cand)->keyval) < _key) { ++level; if((cand)->r) cand = (cand)->r; else return make_tuple((cand),&(cand)->r,level); } else if(_key < _KeyOfVal()((cand)->keyval)) { ++level; if((cand)->l) cand = (cand)->l; else return make_tuple((cand),&(cand)->l,level); } else break; } return make_tuple((cand)->parent, cand->parent->r==cand?&cand->parent->r:&cand->parent->l,level); } // finds a place to insert a new element, possibly equal to some others already present // returns parent's pointer to this node inline SplayNode** _findForInsert(const key_type& _key) // multiset { SplayNode **cand = &superRoot()->l; while(*cand != NULL) { if(_KeyOfVal()((*cand)->keyval) <= _key) cand = &(*cand)->r; else cand = &(*cand)->l; } return cand; } }; ////////////////////////////////////////////////////// (splay tree) //////////// template<typename T, class Node = DefSplayNode<T> > class SplaySet : public SplayTree<T,T,_Identity<T>, Node>{}; } typedef pair<ll,ll> pll; struct point{ ll x,y; }; int n,m; int w,h; struct elem{ bool operator<(const elem&o)const{ return pos.y < o.pos.y; } elem() : pos(point{LLONG_MAX,LLONG_MAX}), val(0) {} elem(point p, int v) : pos(p), val(v) {} point pos; int val; }; vector<elem> elems; point tr(int x, int y){ return point{(ll)x*h - (ll)y*w, (ll)x*h + (ll)y*w}; } struct node : public CopyableSplayNode<elem,node> { typedef CopyableSplayNode<elem,node> B;//ASE // Children-less initialization node(const elem& _keyval, node* _parent) : CopyableSplayNode<elem,node>(_keyval,_parent), sum(0), sufmax(-LLONG_MAX) {} // splay aggregates ll sum; ll sufmax; node* getsufmax(){ if(r && r->sufmax == sufmax) return r->getsufmax(); if(!r && sufmax == keyval.val) return this; if(r && sufmax == r->sum + keyval.val) return this; A(l); if(r && sufmax == r->sum + keyval.val + l->sufmax)return l->getsufmax(); A(!r); A(sufmax == keyval.val + l->sufmax); return l->getsufmax(); } bool getSwapFlag()const {return false;} void setSwapFlag(bool) {} template<int L, int R> void update(){ sum=keyval.val; sufmax = -LLONG_MAX; if(L==1 || (L==0 && l)){ sum += l->sum; if(R==1 || r) sufmax = max(sufmax,l->sufmax + keyval.val + r->sum); else sufmax = max(sufmax,l->sufmax + keyval.val); } if(R==1 || (R==0 && r)){ sum += r->sum; sufmax = max(sufmax,r->sufmax); sufmax = max(sufmax,keyval.val + r->sum); } else sufmax = max(sufmax, (ll)keyval.val); } }; // todo: to powinna byŠ mapa typedef SplaySet<elem,node> SET; SET secik; inline void tc() { E<<"welcome."<<N; I>>n>>m; I>>w>>h; fo(i,n){ int x,y,z; I>>x>>y>>z; elems.pub(elem{tr(x,y),z}); } fo(i,m){ int x,y,z; I>>x>>y>>z; elems.pub(elem{tr(x,y),-z}); } E<<"sort"<<N; sort(all(elems),[](const elem&a,const elem&b){return pll(a.pos.x,-a.pos.y) < pll(b.pos.x,-b.pos.y);}); ll result = 0; fo(i,elems.sz){ E<<N<<"PROCESS "<<elems[i].val<<N; auto&e = elems[i]; auto r = secik.insert(e); A(&*r.fi); if(!r.se){ r.fi->val += e.val; r.fi.getnode()->update<0,0>(); } auto c = r.fi; E<<"inserted "<<c->val<<N; // merge right E<<"begin merging"<<N; for(;;){ if(c->val <= 0) break; auto next = c; ++next; if(next==secik.end()){ E<<"merge right reached end"<<N; A(c->val > 0); E<<"merge me hard, honey, be my -LLONG_MAX"<<N; //secik.find(*c); // splay c->pos.y = -LLONG_MAX; //c.getnode()->update<0,0>(); break; } secik.find(*next); // splay E<<next->val<<" += "<<c->val<<N; next->val += c->val; next.getnode()->update<0,0>(); secik.erase(c); c = next; } E<<"sufmax is now "<<secik.root().sufmax<<N; if(secik.root().sufmax > 0){ E<<"result += "<<secik.root().sufmax<<N; result += secik.root().sufmax; auto ee = secik.root().getsufmax(); A(ee->keyval.val >= 0); SET::iterator it(ee); int dbgnum = 0; for(;;){ auto last = secik.end(); --last; if(last == it)break; secik.erase(last); ++dbgnum; } secik.erase(it); ++dbgnum; E<<" erased "<<dbgnum<<" elements"<<N; } } O<<result<<N; } |