//#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 #include<cstdint> #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." #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> #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(auto&e: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 #include<bits/stdc++.h> #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 pob pop_back #define puf push_front #define pof pop_front #define all(x) (x).begin(),(x).end() #define bs binary_search #define lb lower_bound #define ub upper_bound #define type(x) __typeof(x) #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)) 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{ // 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 uniqueall(T&t){t.resize(unique(t.be,t.en));} 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 #include<type_traits> 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{ //////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// GRAFY //////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // BINDER template<typename Ret, typename T> class Binder { public: Binder(Ret T::*_var) : var(_var) {} Ret& operator()(T& obj) const { return obj.*var; } const Ret& operator()(const T& obj) const { return obj.*var; } private: Ret T::*var; }; template<typename Ret, typename T> Binder<Ret,T> bind(Ret T::*var) { return Binder<Ret,T>(var); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // KLASY GRAFOW // // * wska┼║niki (PE, PV) i iteratory nie mog─ů du┼╝o zajmowa─ç, // bo mog─ů by─ç pami─Ötane przez np. Dinica // * Dlatego s─ů to prawie (ca┼ékiem?) go┼ée wska┼║niki, kt├│re nie zawsze pozwalaj─ů // na wykonanie ┼╝─ůdanej operacji na tym, na co wskazuj─ů, np. usuwania kraw─Ödzi // * Po to s─ů klasy VC i EC (context), kt├│re pozwalaj─ů wykonywa─ç // wszystkie dost─Öpne operacje /* template<uint _NMax = 0, uint _MMax = 0, typename _VExtra = VOID, typename _EExtra = VOID> class G { public: static const uint NMax = _NMax; static const uint MMax = _MMax; typename _VExtra VExtra; typename _EExtra EExtra; struct VC//ontext { struct TO<E> { struct iterator : public PE { // ... }; iterator begin(); iterator end(); EContext operator[](PE&); } to; }; } struct EC//ontext { EExtra& operator->() VContext fr(); VContext to(); EContext rev() const; // rev must be enabled bool revEnabled() const; void erase(); void disable(); // EC becomes invalid void enableRev(); // rev must be disabled } struct PE; struct VS<V> { struct iterator : public PV { // ... }; iterator begin(); iterator end(); VContext operator[](PV&); } vs; struct ES<E> { struct iterator : public PE { // ... }; iterator begin(); iterator end(); EContext operator[](PE&); } es; struct V : public VExtra { V(VContext); }; struct E : public EExtra { E(EContext); }; }; */ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // 2014-05-12 // Vs Es // Iterate no yes // Erase no no // point int pointer // rev no // // Avoid vs reallocation! (?) // // Good for: Kruskal // // dummy vertices // template<typename VExtra=VOID, typename EExtra=VOID, uint NMax=0, uint MMax=0> class GraphU_EI{}; template<typename _EExtra, uint _NMax, uint _MMax> class GraphU_EI<VOID,_EExtra,_NMax,_MMax> // edges iterable { private: class V; class E; public: static const uint NMax = _NMax; static const uint MMax = _MMax; typedef VOID VExtra; typedef _EExtra EExtra; typedef uint PV; typedef E* PE; private: class V : public VExtra{ }; class E : public EExtra{ friend class GraphU_EI; E(const PV& _fr, const PV& _to, const EExtra& eExtra) : EExtra(eExtra), fr(_fr), to(_to) {} PV fr,to; }; public: class VC; class EC; class VS; class ES; class VC{ public: VC(GraphU_EI&_g, const PV& _v) : g(_g), v(_v){} operator PV()const{return v;} private: GraphU_EI& g; PV v; }; class EC{ public: EExtra* operator->(){return e;} template<class T> decltype(PE()->*T()) operator->*(const T& t){return e->*t;} operator PE()const{return e;} VC fr(){return VC(g,e->fr);} VC to(){return VC(g,e->to);} void fr(const PV& _fr){e->fr=_fr;} void to(const PV& _to){e->to=_to;} EC(GraphU_EI&_g, const PE& _e) : g(_g), e(_e) {} private: GraphU_EI& g; PE e; }; class VS{ friend class GraphU_EI; public: typedef uint iterator; uint size()const{return g.vsSize;} void resize(uint _size){g.vsSize=_size;} iterator begin()const{return 0;} iterator end()const{return g.vsSize;} private: GraphU_EI& g; VS(GraphU_EI& _g) : g(_g) {} } vs; class ES{ friend class GraphU_EI; public: typedef PE iterator; inline iterator begin() {return &*g._es.begin();} inline iterator end() {return &*g._es.end();} inline uint size()const{return g._es.size();} inline void resize(unsigned int _size) {g._es.resize(_size);} inline void reserve(unsigned int _size) {g._es.reserve(_size);} inline void push_back(const PV& from, const PV& to, const EExtra& eExtra = EExtra()){ g._es.push_back(E(from,to,eExtra)); } inline EC operator[](const PE& pe) {return EC(g,pe);} inline EC operator[](unsigned int idx){ A(MMax==0 || idx < MMax); return EC(g,&g._es[idx]); } private: GraphU_EI& g; ES(GraphU_EI& _g) : g(_g) {} } es; GraphU_EI() : vs(*this), es(*this), vsSize(0) {} private: typedef typename _vector<E,NMax>::R _ES; _ES _es; uint vsSize; }; //////////////////////////////////////////////////////////////////////////////// // 2013-11-15 // Vs Es // Iterate yes no // Erase no yes // point pointer pointer // rev yes // // Avoid vs reallocation! // Es paired or single // // Good for: Dinic // // use BaseG::VExtra // otherwise use G template<typename _VExtra = VOID, typename _EExtra = VOID, uint _NMax = 0, uint _MMax = 0> class BaseGraphU_ERD { public: static const uint NMax = _NMax; static const uint MMax = _MMax; typedef _VExtra VExtra; typedef _EExtra EExtra; private: class V; class E; public: typedef V* PV; typedef E* PE; typedef typename _vector<V,NMax>::R _VS; public: inline BaseGraphU_ERD(_VS& __vs) : _vs(__vs), vs(*this) {} _VS& _vs; private: struct E : public EExtra { inline E(const PV& _to, const PE& _rev, const EExtra& ee = EExtra()) : EExtra(ee), to(_to), rev(_rev) {} inline E(const E& o) : EExtra(o), to(o.to), rev(o.rev) { if(rev) rev->rev = this; } inline E& operator=(const E& o) { EExtra::operator=(o); to = o.to; rev = o.rev; if(rev) rev->rev = this; return *this; } PV to; PE rev; }; class V : public VExtra { friend class BaseGraphU_ERD; private: std::vector<E> to; }; //_VS& _vs; public: class VC; class EC; class VS; class VC//ontext { friend class VS; friend class EC; public: struct TO { friend class BaseGraphU_ERD; private: BaseGraphU_ERD& g; PV pv; inline TO(BaseGraphU_ERD& _g, PV& _pv) : g(_g), pv(_pv) {} inline void push_back(const E& e) { pv->to.push_back(e); } public: typedef PE iterator; inline iterator begin() {return &*pv->to.begin();} inline iterator end() {return &*pv->to.end();} inline void reserve(unsigned int size) {pv->to.reserve(size);} inline E& back() {return pv->to.back();} inline const E& back() const {return pv->to.back();} inline E& front() {return pv->to.front();} inline const E& front() const {return pv->to.front();} inline EC operator[](PE& pe) { return EC(g,pe,pv); } } to; inline V& operator*() {return *to.pv;} inline const V& operator*() const {return *to.pv;} inline V* operator->() {return to.pv;} inline const V* operator->() const {return to.pv;} inline operator PV() const {return to.pv;} private: inline VC(BaseGraphU_ERD& _g, PV _pv) : to(_g,_pv) {} }; class EC//ontext { friend class VC::TO; public: inline VC to() const {return VC(g,pe->to);} inline EC rev() const {return EC(g,pe->rev,pe->to);} // rev must be enabled inline bool revEnabled() const {return pe->rev != 0;} inline void delSingle() { A(!pe->rev); // single g._delE(pvfrom,pe); } inline void delPaired() { g._delE(pe->to, pe->rev); g._delE(pvfrom, pe); } inline void del() // !!! SLOWER !!! { if(pe->rev) _delE(pe->to, pe->rev); g._delE(pvfrom, pe); } inline void disable() // EC becomes invalid, rev must be enabled { PE reve = pe->rev; g._delE(pvfrom, pe); reve->rev = 0; } inline void enableRev() // rev must be disabled { A(pe->rev==0); pe->rev = &*pe->to->to.begin() + pe->to->to.size(); pe->to->to.push_back(E(pvfrom,pe)); } inline operator PE() const {return pe;} private: inline EC(BaseGraphU_ERD& _g, const PE& _pe, const PV& _pvfrom) : g(_g), pe(_pe), pvfrom(_pvfrom) {} BaseGraphU_ERD& g; PE pe; PV pvfrom; }; class VS { friend class BaseGraphU_ERD; public: typedef PV iterator; inline iterator begin() {return &*g._vs.begin();} inline iterator end() {return &*g._vs.end();} inline void resize(unsigned int size) {g._vs.resize(size);} inline VC operator[](const PV& pv) {return VC(g,pv);} inline VC operator[](unsigned int idx) { A(NMax==0 || idx < NMax); return VC(g,&g._vs[idx]); } private: BaseGraphU_ERD& g; VS(BaseGraphU_ERD& _g) : g(_g) {} } vs; inline void addSingle(PV vot, PV vto, EExtra extra = EExtra()) { vot->to.push_back(E(vto,0,extra)); } inline void addPaired(const PV& vot, const PV& vto, const EExtra& extra1 = EExtra(), const EExtra& extra2 = EExtra()) { vot->to.push_back(E(vto,0,extra1)); vto->to.push_back(E(vot,0,extra2)); vot->to.back().rev = &*vto->to.begin()+vto->to.size()-1; vto->to.back().rev = &*vot->to.begin()+vot->to.size()-1; /* vs[vot].to.push_back(); E& e1 = vs[vot].to.back(); vs[vto].to.push_back(); E& e2 = vs[vto].to.back(); e1.~E(); // avoid copy constructors new(&e1) E(vto, &e2, extra1); e2.~E(); new(&e2) E(vot, &e1, extra2);*/ } private: inline void _delE(const PV& pvfrom, const PE& pe) { *pe = pvfrom->to.back(); pvfrom->to.pop_back(); } }; template<typename _VExtra = VOID, typename _EExtra = VOID, uint _NMax = 0, uint _MMax = 0> class GraphU_ERD // edges removable, disableable : public BaseGraphU_ERD<_VExtra,_EExtra,_NMax,_MMax>//raphU_ERD { public: typedef BaseGraphU_ERD<_VExtra,_EExtra,_NMax,_MMax> BASE; inline GraphU_ERD() : BASE(__vs) {} typename BASE::_VS __vs; }; //////////////////////////////////////////////////////////////////////////////// } #include<cstring> #include<vector> namespace ab{ ////////////////////////////////// UNION FIND ////////////////////////////////// class UnionFind { public: UnionFind(size_t univSize) : parents(univSize), ranks(univSize,0) { for(size_t i=0; i<univSize; ++i) parents[i] = i; } size_t find(size_t x) { size_t root = x; while(parents[root] != root) root = parents[root]; while(x != root) { size_t& curr = parents[x]; x = parents[x]; curr = root; } return root; } bool makeUnion(size_t a, size_t b) // false if union already made { a = find(a); b = find(b); if(a==b)return false; if(ranks[a] < ranks[b]) parents[a] = b, ++ranks[b]; else parents[b] = a, ++ranks[a]; return true; } private: std::vector<size_t> parents; std::vector<size_t> ranks; }; //////////////////////////////////////////////////////////////////////////////// } namespace ab { // MST // O(m log n) // // minNumComponents is optional, for optimization; setting lower than actual number of components is ok // // zeroResult=false wydaje sie nic nie przyspieszac // // sorted=true znacznie przyspiesza. mo┐na u┐yŠ counting sorta wczesniej // #ifdef OLD_COMPILER template<typename G, typename EWeight, typename EResult, bool sorted = false, bool zeroResult=true, int minNumComponents = 1> #else template<bool sorted = false, bool zeroResult=true, int minNumComponents = 1, typename G, typename EWeight, typename EResult> #endif int kruskal(G& g, const EWeight& eWeight, const EResult& eResult) { unsigned int numEdges = g.es.size(); unsigned int numVerts = g.vs.size(); if(!sorted)std::sort(g.es.begin(),g.es.end(),[eWeight](const typename G::EExtra& a, const typename G::EExtra& b){return a.*eWeight < b.*eWeight;}); UnionFind uf(numVerts); int numFound = 0; int i=0; for(; i<numEdges && numFound < numVerts-minNumComponents; ++i) { typename G::PV a = g.es[i].fr(); typename G::PV b = g.es[i].to(); int aa = uf.find(a-g.vs.begin()); int bb = uf.find(b-g.vs.begin()); if(aa==bb){ if(zeroResult)g.es[i]->*eResult = false; continue; } uf.makeUnion(aa,bb); ++numFound; g.es[i]->*eResult = true; } if(zeroResult) for(;i<numEdges;++i) g.es[i]->*eResult = false; return numFound; } #ifdef OLD_COMPILER template<typename G, typename EWeight, bool sorted = false, unsigned int minNumComponents = 1> #else template<bool sorted = false, unsigned int minNumComponents = 1, typename G, typename EWeight> #endif std::vector<typename G::PE> kruskal(G& g, const EWeight& eWeight) { unsigned int numEdges = g.es.size(); unsigned int numVerts = g.vs.size(); if(!sorted)std::sort(g.es.begin(),g.es.end(),[eWeight](const typename G::EExtra& a, const typename G::EExtra& b){return a.*eWeight < b.*eWeight;}); UnionFind uf(numVerts); std::vector<typename G::PE> result; result.reserve(numVerts-minNumComponents); for(int i=0; i<numEdges && result.size() < numVerts-minNumComponents; ++i) { typename G::PV a = g.es[i].fr(); typename G::PV b = g.es[i].to(); int aa = uf.find(a-g.vs.begin()); int bb = uf.find(b-g.vs.begin()); if(aa==bb)continue; uf.makeUnion(aa,bb); result.push_back(g.es[i]); } return result; } template<typename Weight> struct _boruvkaCleanupEdge { int from; int to; Weight val; int orig; static int getFrom(const _boruvkaCleanupEdge& e) { return e.from; } static int getTo(const _boruvkaCleanupEdge& e) { return e.to; } }; /* // MST // sets resultEDataKey to true for edges in MST, does not set resultEDataKey for other edges // O(min(m log n, n^2)) // O(n) if planar // set cleanupfirst = false if there are no multiple (u,v) edges // Old paper by Cheriton, ... template<bool cleanupFirst = true, typename G, typename EWeight> std::vector<G::PE> boruvkaCleanup(G& g, const EWeight& eWeight) { int numTrees = g.vs.size(); std::vector<_boruvkaCleanupEdge<Weight>> edges(g.edges.size()); for(unsigned int i=0; i<g.edges.size(); ++i) { edges[i].from = g.edges[i].from; edges[i].to = g.edges[i].to; edges[i].val = getWeightEData(g.edges[i]); edges[i].orig = i; } std::pair<int,Weight> *bests = new std::pair<int,Weight>[numTrees]; int *vmap = new int[numTrees]; int numFound = 0; for(;;) { // cleanup if(numFound != 0 || cleanupFirst) { std::vector<_boruvkaCleanupEdge<Weight> > helperEdges(edges.size()); countingSort(&edges[0], &edges[0] + edges.size(), &helperEdges[0], numTrees, _boruvkaCleanupEdge<Weight>::getTo); countingSort(&helperEdges[0], &helperEdges[0] + edges.size(), &edges[0], numTrees, _boruvkaCleanupEdge<Weight>::getFrom); int curDest = 0; int prev1 = -1; int prev2 = -1; Weight bestval = 0; int bestarg = 0; //printf("edges size %d\n", edges.size()); for(unsigned int i=0; i<edges.size(); ++i) { int n1 = edges[i].from; int n2 = edges[i].to; if(n1 == n2) continue; if(prev1 == n1 && prev2 == n2) { if(edges[i].val < bestval) bestval = edges[i].val, bestarg = i; } else { if(prev1 != -1) edges[curDest++] = edges[bestarg]; bestval = edges[i].val; bestarg = i; prev1 = n1; prev2 = n2; } } if(prev1 != -1) edges[curDest++] = edges[bestarg]; edges.resize(curDest); } //cleanup end //printf("Cheriton step: %d trees, %d edges, found %d\n",numTrees,edges.size(),numFound); // find bests memset(bests, 0xff, sizeof(std::pair<int,Weight>)*numTrees); for(unsigned int i=0; i<edges.size(); ++i) { //printf("%x\n",bests[a].first); int a = edges[i].from; if((unsigned int)bests[a].first == 0xffffffff || bests[a].second > edges[i].val) { bests[a].second = edges[i].val; bests[a].first = i; } int b = edges[i].to; if((unsigned int)bests[b].first == 0xffffffff || bests[b].second > edges[i].val) { bests[b].second = edges[i].val; bests[b].first = i; } } // find bests end UnionFind uf(numTrees); bool change = false; for(int i=0; i<numTrees; ++i) { int best = bests[i].first; if((unsigned int)best == 0xffffffff) continue; int a = edges[best].from; int b = edges[best].to; a = uf.find(a); b = uf.find(b); if(a==b)continue; uf.makeUnion(a,b); getResultEData(g.edges[edges[best].orig]) = true; ++numFound; change = true; } if(!change) break; // przemianowanie int newNumTrees = 0; memset(vmap, 0xff, sizeof(int)*numTrees); for(int i=0; i<numTrees; ++i) { int a = uf.find(i); if((unsigned int)vmap[a] == 0xffffffff) vmap[a] = newNumTrees++; vmap[i] = vmap[a]; } for(unsigned int i=0; i<edges.size(); ++i) { edges[i].from = vmap[edges[i].from]; edges[i].to = vmap[edges[i].to]; } numTrees = newNumTrees; // przemianowanie end } delete[] bests; delete[] vmap; return numFound; } */ } struct EExtra{ int weight; }; typedef GraphU_EI<VOID,EExtra> G; inline void tc() { uint n; I>>n; G g; g.vs.resize(n+1); g.es.reserve(n*(n+1)/2); fo(i,n)fo(j,i+1,n+1){ int val = rint; g.es.pub(i,j,EExtra{val}); } auto result = kruskal(g,&EExtra::weight); A(result.sz+1 == n); // tree ui64 r = 0; fo(i,result.sz)r += result[i]->weight; O<<r<<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 | //#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 #include<cstdint> #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." #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> #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(auto&e: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 #include<bits/stdc++.h> #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 pob pop_back #define puf push_front #define pof pop_front #define all(x) (x).begin(),(x).end() #define bs binary_search #define lb lower_bound #define ub upper_bound #define type(x) __typeof(x) #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)) 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{ // 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 uniqueall(T&t){t.resize(unique(t.be,t.en));} 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 #include<type_traits> 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{ //////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// GRAFY //////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // BINDER template<typename Ret, typename T> class Binder { public: Binder(Ret T::*_var) : var(_var) {} Ret& operator()(T& obj) const { return obj.*var; } const Ret& operator()(const T& obj) const { return obj.*var; } private: Ret T::*var; }; template<typename Ret, typename T> Binder<Ret,T> bind(Ret T::*var) { return Binder<Ret,T>(var); } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // KLASY GRAFOW // // * wska┼║niki (PE, PV) i iteratory nie mog─ů du┼╝o zajmowa─ç, // bo mog─ů by─ç pami─Ötane przez np. Dinica // * Dlatego s─ů to prawie (ca┼ékiem?) go┼ée wska┼║niki, kt├│re nie zawsze pozwalaj─ů // na wykonanie ┼╝─ůdanej operacji na tym, na co wskazuj─ů, np. usuwania kraw─Ödzi // * Po to s─ů klasy VC i EC (context), kt├│re pozwalaj─ů wykonywa─ç // wszystkie dost─Öpne operacje /* template<uint _NMax = 0, uint _MMax = 0, typename _VExtra = VOID, typename _EExtra = VOID> class G { public: static const uint NMax = _NMax; static const uint MMax = _MMax; typename _VExtra VExtra; typename _EExtra EExtra; struct VC//ontext { struct TO<E> { struct iterator : public PE { // ... }; iterator begin(); iterator end(); EContext operator[](PE&); } to; }; } struct EC//ontext { EExtra& operator->() VContext fr(); VContext to(); EContext rev() const; // rev must be enabled bool revEnabled() const; void erase(); void disable(); // EC becomes invalid void enableRev(); // rev must be disabled } struct PE; struct VS<V> { struct iterator : public PV { // ... }; iterator begin(); iterator end(); VContext operator[](PV&); } vs; struct ES<E> { struct iterator : public PE { // ... }; iterator begin(); iterator end(); EContext operator[](PE&); } es; struct V : public VExtra { V(VContext); }; struct E : public EExtra { E(EContext); }; }; */ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // 2014-05-12 // Vs Es // Iterate no yes // Erase no no // point int pointer // rev no // // Avoid vs reallocation! (?) // // Good for: Kruskal // // dummy vertices // template<typename VExtra=VOID, typename EExtra=VOID, uint NMax=0, uint MMax=0> class GraphU_EI{}; template<typename _EExtra, uint _NMax, uint _MMax> class GraphU_EI<VOID,_EExtra,_NMax,_MMax> // edges iterable { private: class V; class E; public: static const uint NMax = _NMax; static const uint MMax = _MMax; typedef VOID VExtra; typedef _EExtra EExtra; typedef uint PV; typedef E* PE; private: class V : public VExtra{ }; class E : public EExtra{ friend class GraphU_EI; E(const PV& _fr, const PV& _to, const EExtra& eExtra) : EExtra(eExtra), fr(_fr), to(_to) {} PV fr,to; }; public: class VC; class EC; class VS; class ES; class VC{ public: VC(GraphU_EI&_g, const PV& _v) : g(_g), v(_v){} operator PV()const{return v;} private: GraphU_EI& g; PV v; }; class EC{ public: EExtra* operator->(){return e;} template<class T> decltype(PE()->*T()) operator->*(const T& t){return e->*t;} operator PE()const{return e;} VC fr(){return VC(g,e->fr);} VC to(){return VC(g,e->to);} void fr(const PV& _fr){e->fr=_fr;} void to(const PV& _to){e->to=_to;} EC(GraphU_EI&_g, const PE& _e) : g(_g), e(_e) {} private: GraphU_EI& g; PE e; }; class VS{ friend class GraphU_EI; public: typedef uint iterator; uint size()const{return g.vsSize;} void resize(uint _size){g.vsSize=_size;} iterator begin()const{return 0;} iterator end()const{return g.vsSize;} private: GraphU_EI& g; VS(GraphU_EI& _g) : g(_g) {} } vs; class ES{ friend class GraphU_EI; public: typedef PE iterator; inline iterator begin() {return &*g._es.begin();} inline iterator end() {return &*g._es.end();} inline uint size()const{return g._es.size();} inline void resize(unsigned int _size) {g._es.resize(_size);} inline void reserve(unsigned int _size) {g._es.reserve(_size);} inline void push_back(const PV& from, const PV& to, const EExtra& eExtra = EExtra()){ g._es.push_back(E(from,to,eExtra)); } inline EC operator[](const PE& pe) {return EC(g,pe);} inline EC operator[](unsigned int idx){ A(MMax==0 || idx < MMax); return EC(g,&g._es[idx]); } private: GraphU_EI& g; ES(GraphU_EI& _g) : g(_g) {} } es; GraphU_EI() : vs(*this), es(*this), vsSize(0) {} private: typedef typename _vector<E,NMax>::R _ES; _ES _es; uint vsSize; }; //////////////////////////////////////////////////////////////////////////////// // 2013-11-15 // Vs Es // Iterate yes no // Erase no yes // point pointer pointer // rev yes // // Avoid vs reallocation! // Es paired or single // // Good for: Dinic // // use BaseG::VExtra // otherwise use G template<typename _VExtra = VOID, typename _EExtra = VOID, uint _NMax = 0, uint _MMax = 0> class BaseGraphU_ERD { public: static const uint NMax = _NMax; static const uint MMax = _MMax; typedef _VExtra VExtra; typedef _EExtra EExtra; private: class V; class E; public: typedef V* PV; typedef E* PE; typedef typename _vector<V,NMax>::R _VS; public: inline BaseGraphU_ERD(_VS& __vs) : _vs(__vs), vs(*this) {} _VS& _vs; private: struct E : public EExtra { inline E(const PV& _to, const PE& _rev, const EExtra& ee = EExtra()) : EExtra(ee), to(_to), rev(_rev) {} inline E(const E& o) : EExtra(o), to(o.to), rev(o.rev) { if(rev) rev->rev = this; } inline E& operator=(const E& o) { EExtra::operator=(o); to = o.to; rev = o.rev; if(rev) rev->rev = this; return *this; } PV to; PE rev; }; class V : public VExtra { friend class BaseGraphU_ERD; private: std::vector<E> to; }; //_VS& _vs; public: class VC; class EC; class VS; class VC//ontext { friend class VS; friend class EC; public: struct TO { friend class BaseGraphU_ERD; private: BaseGraphU_ERD& g; PV pv; inline TO(BaseGraphU_ERD& _g, PV& _pv) : g(_g), pv(_pv) {} inline void push_back(const E& e) { pv->to.push_back(e); } public: typedef PE iterator; inline iterator begin() {return &*pv->to.begin();} inline iterator end() {return &*pv->to.end();} inline void reserve(unsigned int size) {pv->to.reserve(size);} inline E& back() {return pv->to.back();} inline const E& back() const {return pv->to.back();} inline E& front() {return pv->to.front();} inline const E& front() const {return pv->to.front();} inline EC operator[](PE& pe) { return EC(g,pe,pv); } } to; inline V& operator*() {return *to.pv;} inline const V& operator*() const {return *to.pv;} inline V* operator->() {return to.pv;} inline const V* operator->() const {return to.pv;} inline operator PV() const {return to.pv;} private: inline VC(BaseGraphU_ERD& _g, PV _pv) : to(_g,_pv) {} }; class EC//ontext { friend class VC::TO; public: inline VC to() const {return VC(g,pe->to);} inline EC rev() const {return EC(g,pe->rev,pe->to);} // rev must be enabled inline bool revEnabled() const {return pe->rev != 0;} inline void delSingle() { A(!pe->rev); // single g._delE(pvfrom,pe); } inline void delPaired() { g._delE(pe->to, pe->rev); g._delE(pvfrom, pe); } inline void del() // !!! SLOWER !!! { if(pe->rev) _delE(pe->to, pe->rev); g._delE(pvfrom, pe); } inline void disable() // EC becomes invalid, rev must be enabled { PE reve = pe->rev; g._delE(pvfrom, pe); reve->rev = 0; } inline void enableRev() // rev must be disabled { A(pe->rev==0); pe->rev = &*pe->to->to.begin() + pe->to->to.size(); pe->to->to.push_back(E(pvfrom,pe)); } inline operator PE() const {return pe;} private: inline EC(BaseGraphU_ERD& _g, const PE& _pe, const PV& _pvfrom) : g(_g), pe(_pe), pvfrom(_pvfrom) {} BaseGraphU_ERD& g; PE pe; PV pvfrom; }; class VS { friend class BaseGraphU_ERD; public: typedef PV iterator; inline iterator begin() {return &*g._vs.begin();} inline iterator end() {return &*g._vs.end();} inline void resize(unsigned int size) {g._vs.resize(size);} inline VC operator[](const PV& pv) {return VC(g,pv);} inline VC operator[](unsigned int idx) { A(NMax==0 || idx < NMax); return VC(g,&g._vs[idx]); } private: BaseGraphU_ERD& g; VS(BaseGraphU_ERD& _g) : g(_g) {} } vs; inline void addSingle(PV vot, PV vto, EExtra extra = EExtra()) { vot->to.push_back(E(vto,0,extra)); } inline void addPaired(const PV& vot, const PV& vto, const EExtra& extra1 = EExtra(), const EExtra& extra2 = EExtra()) { vot->to.push_back(E(vto,0,extra1)); vto->to.push_back(E(vot,0,extra2)); vot->to.back().rev = &*vto->to.begin()+vto->to.size()-1; vto->to.back().rev = &*vot->to.begin()+vot->to.size()-1; /* vs[vot].to.push_back(); E& e1 = vs[vot].to.back(); vs[vto].to.push_back(); E& e2 = vs[vto].to.back(); e1.~E(); // avoid copy constructors new(&e1) E(vto, &e2, extra1); e2.~E(); new(&e2) E(vot, &e1, extra2);*/ } private: inline void _delE(const PV& pvfrom, const PE& pe) { *pe = pvfrom->to.back(); pvfrom->to.pop_back(); } }; template<typename _VExtra = VOID, typename _EExtra = VOID, uint _NMax = 0, uint _MMax = 0> class GraphU_ERD // edges removable, disableable : public BaseGraphU_ERD<_VExtra,_EExtra,_NMax,_MMax>//raphU_ERD { public: typedef BaseGraphU_ERD<_VExtra,_EExtra,_NMax,_MMax> BASE; inline GraphU_ERD() : BASE(__vs) {} typename BASE::_VS __vs; }; //////////////////////////////////////////////////////////////////////////////// } #include<cstring> #include<vector> namespace ab{ ////////////////////////////////// UNION FIND ////////////////////////////////// class UnionFind { public: UnionFind(size_t univSize) : parents(univSize), ranks(univSize,0) { for(size_t i=0; i<univSize; ++i) parents[i] = i; } size_t find(size_t x) { size_t root = x; while(parents[root] != root) root = parents[root]; while(x != root) { size_t& curr = parents[x]; x = parents[x]; curr = root; } return root; } bool makeUnion(size_t a, size_t b) // false if union already made { a = find(a); b = find(b); if(a==b)return false; if(ranks[a] < ranks[b]) parents[a] = b, ++ranks[b]; else parents[b] = a, ++ranks[a]; return true; } private: std::vector<size_t> parents; std::vector<size_t> ranks; }; //////////////////////////////////////////////////////////////////////////////// } namespace ab { // MST // O(m log n) // // minNumComponents is optional, for optimization; setting lower than actual number of components is ok // // zeroResult=false wydaje sie nic nie przyspieszac // // sorted=true znacznie przyspiesza. mo┐na u┐yŠ counting sorta wczesniej // #ifdef OLD_COMPILER template<typename G, typename EWeight, typename EResult, bool sorted = false, bool zeroResult=true, int minNumComponents = 1> #else template<bool sorted = false, bool zeroResult=true, int minNumComponents = 1, typename G, typename EWeight, typename EResult> #endif int kruskal(G& g, const EWeight& eWeight, const EResult& eResult) { unsigned int numEdges = g.es.size(); unsigned int numVerts = g.vs.size(); if(!sorted)std::sort(g.es.begin(),g.es.end(),[eWeight](const typename G::EExtra& a, const typename G::EExtra& b){return a.*eWeight < b.*eWeight;}); UnionFind uf(numVerts); int numFound = 0; int i=0; for(; i<numEdges && numFound < numVerts-minNumComponents; ++i) { typename G::PV a = g.es[i].fr(); typename G::PV b = g.es[i].to(); int aa = uf.find(a-g.vs.begin()); int bb = uf.find(b-g.vs.begin()); if(aa==bb){ if(zeroResult)g.es[i]->*eResult = false; continue; } uf.makeUnion(aa,bb); ++numFound; g.es[i]->*eResult = true; } if(zeroResult) for(;i<numEdges;++i) g.es[i]->*eResult = false; return numFound; } #ifdef OLD_COMPILER template<typename G, typename EWeight, bool sorted = false, unsigned int minNumComponents = 1> #else template<bool sorted = false, unsigned int minNumComponents = 1, typename G, typename EWeight> #endif std::vector<typename G::PE> kruskal(G& g, const EWeight& eWeight) { unsigned int numEdges = g.es.size(); unsigned int numVerts = g.vs.size(); if(!sorted)std::sort(g.es.begin(),g.es.end(),[eWeight](const typename G::EExtra& a, const typename G::EExtra& b){return a.*eWeight < b.*eWeight;}); UnionFind uf(numVerts); std::vector<typename G::PE> result; result.reserve(numVerts-minNumComponents); for(int i=0; i<numEdges && result.size() < numVerts-minNumComponents; ++i) { typename G::PV a = g.es[i].fr(); typename G::PV b = g.es[i].to(); int aa = uf.find(a-g.vs.begin()); int bb = uf.find(b-g.vs.begin()); if(aa==bb)continue; uf.makeUnion(aa,bb); result.push_back(g.es[i]); } return result; } template<typename Weight> struct _boruvkaCleanupEdge { int from; int to; Weight val; int orig; static int getFrom(const _boruvkaCleanupEdge& e) { return e.from; } static int getTo(const _boruvkaCleanupEdge& e) { return e.to; } }; /* // MST // sets resultEDataKey to true for edges in MST, does not set resultEDataKey for other edges // O(min(m log n, n^2)) // O(n) if planar // set cleanupfirst = false if there are no multiple (u,v) edges // Old paper by Cheriton, ... template<bool cleanupFirst = true, typename G, typename EWeight> std::vector<G::PE> boruvkaCleanup(G& g, const EWeight& eWeight) { int numTrees = g.vs.size(); std::vector<_boruvkaCleanupEdge<Weight>> edges(g.edges.size()); for(unsigned int i=0; i<g.edges.size(); ++i) { edges[i].from = g.edges[i].from; edges[i].to = g.edges[i].to; edges[i].val = getWeightEData(g.edges[i]); edges[i].orig = i; } std::pair<int,Weight> *bests = new std::pair<int,Weight>[numTrees]; int *vmap = new int[numTrees]; int numFound = 0; for(;;) { // cleanup if(numFound != 0 || cleanupFirst) { std::vector<_boruvkaCleanupEdge<Weight> > helperEdges(edges.size()); countingSort(&edges[0], &edges[0] + edges.size(), &helperEdges[0], numTrees, _boruvkaCleanupEdge<Weight>::getTo); countingSort(&helperEdges[0], &helperEdges[0] + edges.size(), &edges[0], numTrees, _boruvkaCleanupEdge<Weight>::getFrom); int curDest = 0; int prev1 = -1; int prev2 = -1; Weight bestval = 0; int bestarg = 0; //printf("edges size %d\n", edges.size()); for(unsigned int i=0; i<edges.size(); ++i) { int n1 = edges[i].from; int n2 = edges[i].to; if(n1 == n2) continue; if(prev1 == n1 && prev2 == n2) { if(edges[i].val < bestval) bestval = edges[i].val, bestarg = i; } else { if(prev1 != -1) edges[curDest++] = edges[bestarg]; bestval = edges[i].val; bestarg = i; prev1 = n1; prev2 = n2; } } if(prev1 != -1) edges[curDest++] = edges[bestarg]; edges.resize(curDest); } //cleanup end //printf("Cheriton step: %d trees, %d edges, found %d\n",numTrees,edges.size(),numFound); // find bests memset(bests, 0xff, sizeof(std::pair<int,Weight>)*numTrees); for(unsigned int i=0; i<edges.size(); ++i) { //printf("%x\n",bests[a].first); int a = edges[i].from; if((unsigned int)bests[a].first == 0xffffffff || bests[a].second > edges[i].val) { bests[a].second = edges[i].val; bests[a].first = i; } int b = edges[i].to; if((unsigned int)bests[b].first == 0xffffffff || bests[b].second > edges[i].val) { bests[b].second = edges[i].val; bests[b].first = i; } } // find bests end UnionFind uf(numTrees); bool change = false; for(int i=0; i<numTrees; ++i) { int best = bests[i].first; if((unsigned int)best == 0xffffffff) continue; int a = edges[best].from; int b = edges[best].to; a = uf.find(a); b = uf.find(b); if(a==b)continue; uf.makeUnion(a,b); getResultEData(g.edges[edges[best].orig]) = true; ++numFound; change = true; } if(!change) break; // przemianowanie int newNumTrees = 0; memset(vmap, 0xff, sizeof(int)*numTrees); for(int i=0; i<numTrees; ++i) { int a = uf.find(i); if((unsigned int)vmap[a] == 0xffffffff) vmap[a] = newNumTrees++; vmap[i] = vmap[a]; } for(unsigned int i=0; i<edges.size(); ++i) { edges[i].from = vmap[edges[i].from]; edges[i].to = vmap[edges[i].to]; } numTrees = newNumTrees; // przemianowanie end } delete[] bests; delete[] vmap; return numFound; } */ } struct EExtra{ int weight; }; typedef GraphU_EI<VOID,EExtra> G; inline void tc() { uint n; I>>n; G g; g.vs.resize(n+1); g.es.reserve(n*(n+1)/2); fo(i,n)fo(j,i+1,n+1){ int val = rint; g.es.pub(i,j,EExtra{val}); } auto result = kruskal(g,&EExtra::weight); A(result.sz+1 == n); // tree ui64 r = 0; fo(i,result.sz)r += result[i]->weight; O<<r<<N; } |