//#define READ_NUM_TEST_CASES //#define ASSERTS // force asserts on online judge #define FASTIO //#include<atablash/splay/common.hpp> //#include<atablash/splay/node.hpp> //#include<atablash/interval-tree.hpp> //#include<atablash/hash.hpp> //typedef H1<1000000007> H; //////////////////////////////////////////////////////////////////////////////// // // // ACTUAL 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 // PRIi64, PRIui64 #define __STDC_FORMAT_MACROS #include<inttypes.h> //#include<type_traits> #define _CAT(a,b) a##b #define CAT(a,b) _CAT(a,b) #define _10TH(a,b,c,d,e,f,g,h,i,X,...) X #define VA_CNT(...) _10TH(__VA_ARGS__,9,8,7,6,5,4,3,2,1,0) #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,0) #define VA_GTONE(a,...) CAT(a,_VA_GTONE(__VA_ARGS__))(__VA_ARGS__) #define MIN_GCC(a,b,c) (__GNUC__ > (a) || \ (__GNUC__ == (a) && (__GNUC_MINOR__ > (b) || \ (__GNUC_MINOR__ == (b) && \ __GNUC_PATCHLEVEL__ >= (c))))) // TODO: po co to bylo?? /* #include<functional> #if __cplusplus >= 201103L namespace std { template<class T> struct hash { typedef T argument_type; typedef typename std::underlying_type< argument_type >::type underlying_type; typedef typename std::hash< underlying_type >::result_type result_type; result_type operator()( const argument_type& arg ) const { std::hash< underlying_type > hasher; return hasher( static_cast< underlying_type >( arg ) ); } }; } #endif */ #define bac back() #define fro front() #define emp empty() #define fi first #define se second #define siz size() #define ins insert #define era erase #define mp make_pair #define be begin() #define en end() #define rbe rbegin() #define ren rend() #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 pq priority_queue #define si (int) #undef FO #undef OF #define FOR(i,n) for(int i=0; i<(int)(n); ++i) #define FO(i,a,b) for(int i=(a); i<(int)(b); ++i) #define OF(i,a,b) for(int i=(int)(b)-1;i>=(int)(a);--i) #define FE(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it) #define FER(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ) #define ALL(c) (c).begin(),(c).end() #define ZERO(c) memset(c,0,sizeof(c)) #define AU(v,val) __typeof(val) v(val) const char NL='\n'; const char SP=' '; #include<stdint.h> #include<utility> #include<vector> #include<memory> // abbrevs typedef unsigned int uint; 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 std::pair<double,double> pdd; typedef std::vector<i32> vi; #define VE std::vector #define umap std::unordered_map #define umultimap std::unordered_multimap #define uset std::unordered_set #define umultiset std::unordered_multiset typedef unsigned short ushort; typedef unsigned char uchar; template<class T> using sptr = std::shared_ptr<T>; template<class T> using uptr = std::unique_ptr<T>; template<class A, class B> using p = std::pair<A, B>; namespace ab{ struct Void {}; // convert to float with enough precision 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;}; // get type capable of storing multiplication result 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__ && ( defined __x86_64__ || defined __ppc64__ || defined __MINGW64__ ) typedef __int128_t i128; typedef __uint128_t ui128; template<>struct Double<i64>{typedef i128 R;}; template<>struct Double<ui64>{typedef ui128 R;}; #endif } // Visual C++ intristics #ifdef _MSC_VER #include <intrin.h> #define __builtin_popcount __popcnt #ifdef _WIN64 #define __builtin_popcountll __popcnt64 #else inline int __builtin_popcountll(__int64 a){ return __builtin_popcount((ui32)a) + __builtin_popcount(a >> 32); } #endif #endif // Visual C++ 'and', 'or', 'not' #ifdef _MSC_VER #define and && #define or || #define not ! #endif namespace ab{ template<class T>inline T cbitl(T x,int i){return (x<<i) ^ (x>>(sizeof(T)*8-i));} // cycle bits left inline int popcount(uint i){return __builtin_popcount(i);} inline int popcount(ull i){return __builtin_popcountll(i);} #ifdef __GNUC__ inline int parity(uint i){return __builtin_parity(i);} inline int parity(ull i){return __builtin_parityll(i);} inline int ilog2(uint i){return 31-__builtin_clz(i);} // int log; floor(log2(i)) inline int ilog2(ull i){return 63-__builtin_clzll(i);} #endif template<class T>inline bool isPowerOf2(const T&x){return !(x&(x-1));} struct Static{ Static() = default; Static(const Static&) = delete; Static(Static&&) = delete; Static(const Static&&) = delete; Static& operator=(const Static&) = delete; Static& operator=(Static&&) = delete; Static& operator=(const Static&&) = delete; }; } //#if MIN_GCC(4,1,3) //#include<bits/stdc++.h> //#else #include<vector> #include<map> #include<queue> #include<algorithm> #include<string> #include<stdint.h> #include<cstring> #include<iostream> #include<set> #include<climits> #include<bitset> #include<limits> #include<sstream> #include<cmath> //#endif // enable debug if any debug macro is defined #if (defined _DEBUG || defined DEBUG) && !defined DEBUG_BUILD #define DEBUG_BUILD #endif // DEBUG_BUILD (set or not set) overrides NDEBUG #ifdef DEBUG_BUILD #undef NDEBUG //#pragma message "Compiling in DEBUG mode." #else #ifndef NDEBUG #define NDEBUG #endif #endif //#include <cstdio> //#include <cfloat> #include<vector> #include<unordered_map> // ? #include<iostream> #include<fstream> #include<string> #include<algorithm> #include<mutex> // to_string fix for MinGW #include<map> #include<iostream> #if __cplusplus >= 201103L or defined _MSC_VER #include <unordered_map> #include <unordered_set> namespace std{ #else #include <ext/hash_map> #include <ext/hash_set> namespace __gnu_cxx{ #define unordered_map hash_map #define unordered_multimap hash_multimap #define unordered_set hash_set #define unordered_multiset hash_multiset /* template<class K, class V> class unordered_map : public hash_map<K,V>{ public: typename hash_map<K,V>::iterator erase(const typename hash_map<K,V>::iterator& it){ typename hash_map<K,V>::iterator r = it; ++r; if(r!=hash_map<K,V>::end()){ K key = r->first; hash_map<K,V>::erase(it); return hash_map<K,V>::find(key); } else{ hash_map<K,V>::erase(it); return r; } } typename hash_map<K,V>::size_type erase(const K& key){ return hash_map<K,V>::erase(key); } }; */ #endif // 1,2,last (!!!!!) /*template<>*/ template<class A,class B>struct hash<std::map<A,B> >{ size_t operator()(const std::map<A,B>& m) const{ size_t r = m.size(); if(!r)return 0; __typeof(m.begin()) i=m.be; r^=hash<__typeof(i)>()(i); ++i; r^=cbitl(hash<__typeof(i)>()(*i),sizeof(r)*8/4); i=m.end(); --i; r^=cbitl(hash<__typeof(i)>()(*i),sizeof(r)*8/2); return r; } }; // hash pairs: /*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) ^ ab::cbitl(hash<B>()(p.second),sizeof(size_t)*8/2); } }; // hash enums: // // TODO: fix for msvc #if defined __GNUC__ and MIN_GCC(4,8,4) template<class E> struct hash { using sfinae = typename std::enable_if<std::is_enum<E>::value, E>::type; public: size_t operator()(const E&e) const { return std::hash<typename std::underlying_type<E>::type>()((typename std::underlying_type<E>::type)e); } }; #endif } // namespace std / __gnu_cxx // component-wise pair operators template<class A, class B, class C, class D> inline std::pair<A,B>& operator+=(std::pair<A,B>& p, const std::pair<C,D>& o){ p.first+=o.first; p.second+=o.second; return p; } template<class A, class B, class C, class D> inline std::pair<A,B>& operator-=(std::pair<A,B>& p, const std::pair<C,D>& o){ p.first-=o.first; p.second-=o.second; return p; } template<class A, class B, class C, class D> inline std::pair<A,B>& operator*=(std::pair<A,B>& p, const std::pair<C,D>& o){ p.first*=o.first; p.second*=o.second; return p; } template<class A, class B, class C, class D> inline std::pair<A,B>& operator/=(std::pair<A,B>& p, const std::pair<C,D>& o){ p.first/=o.first; p.second/=o.second; return p; } template<class Afi, class Ase, class Bfi, class Bse> inline std::pair<decltype(Afi() + Bfi()), decltype(Ase() + Bse())>& operator+(const std::pair<Afi,Ase>& a, const std::pair<Bfi,Bse>& b){ return std::make_pair(a.fi+b.fi, a.se+b.se); } template<class Afi, class Ase, class Bfi, class Bse> inline std::pair<decltype(Afi() - Bfi()), decltype(Ase() - Bse())>& operator-(const std::pair<Afi,Ase>& a, const std::pair<Bfi,Bse>& b){ return std::make_pair(a.fi-b.fi, a.se-b.se); } template<class Afi, class Ase, class Bfi, class Bse> inline std::pair<decltype(Afi()*Bfi()), decltype(Ase()*Bse())>& operator*(const std::pair<Afi,Ase>& a, const std::pair<Bfi,Bse>& b){ return std::make_pair(a.fi*b.fi, a.se*b.se); } template<class Afi, class Ase, class Bfi, class Bse> inline std::pair<decltype(Afi() / Bfi()), decltype(Ase() / Bse())>& operator/(const std::pair<Afi,Ase>& a, const std::pair<Bfi,Bse>& b){ return std::make_pair(a.fi/b.fi, a.se/b.se); } // vector operators template<class T, class U> inline std::vector<T>& operator+=(std::vector<T>& v, const std::vector<U>& o){ ASS(v.siz == o.siz); FOR(i,v.siz) v[i] += o[i]; return v; } template<class T> inline std::vector<T>& operator*=(std::vector<T>& v, const T& a){ FOR(i,v.siz) v[i] *= a; return v; } // serialization template<class A,class B>inline std::ostream&operator<<(std::ostream&o,const std::pair<A,B>&p){o<<'<'<<p.first<<", "<<p.second<<'>';return o;} template<class A,class B>inline std::ostream&operator<<(std::ostream&o,const std::map<A,B>&m){o<<'\n';FE(k,m)o<<"map["<<k->first<<"] -> "<<k->se<<'\n';return o;} template<class A,class B>inline std::ostream&operator<<(std::ostream&o,const umap<A,B>&m){o<<'\n';FE(k,m)o<<"umap["<<k->first<<"] -> "<<k->se<<'\n';return o;} template<class A,class B>inline std::ostream&operator<<(std::ostream&o,const uset<A,B>&_m){o<<"uset{\n";FE(k,_m)o<<*k<<'\n';o<<'\n';return o;} template<class A>inline std::ostream&operator<<(std::ostream&o,const std::vector<A>&_v){o<<'\n';FOR(i,_v.siz)o<<"vector["<<i<<"] = "<<_v[i]<<"}\n";return o;} // fix for MinGW: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52015 #ifdef _GLIBCXX_HAVE_BROKEN_VSWPRINTF namespace std{ template<class T> inline string to_string(const T& t){ stringstream ss; ss << t; return ss.str(); } } #endif //#define LOG0(str) fprintf(stderr,"%s:%d - " str "\n",__FILE__,__LINE__) //#define LOG1(str,...) fprintf(stderr,"%s:%d - " str "\n",__FILE__,__LINE__,__VA_ARGS__) //#define LOG(...) VA_GTONE(LOG,__VA_ARGS__) #define LOGD(str) if(ab::Log::global()) ab::Log::global()->debug(str,__FILE__,__LINE__) #define LOGI(str) if(ab::Log::global()) ab::Log::global()->info(str,__FILE__,__LINE__) #define LOGW(str) if(ab::Log::global()) ab::Log::global()->warning(str,__FILE__,__LINE__) #define LOGE(str) if(ab::Log::global()) ab::Log::global()->error(str,__FILE__,__LINE__) #define LOGF(str) if(ab::Log::global()) ab::Log::global()->fail(str,__FILE__,__LINE__) namespace ab{ // TODO: czas logowania // TODO: interfejs do dodawania nazw message levelom, ustawiania nazwy pliku z logiem, czy printowac na stderr, ... // // level >= DEBUG powoduje ignorowanie logowania w release class Log{ public: enum{ DEBUG = 5000, INFO = 4000, // default? WARNING = 3000, ERROR = 2000, FAIL = 1000}; public: void debug(const std::string& _message, const std::string& file="", int line=0){ message(DEBUG, _message, file, line); } void info(const std::string& _message, const std::string& file = "", int line = 0){ message(INFO, _message, file, line); } void warning(const std::string& _message, const std::string& file = "", int line = 0){ message(WARNING, _message, file, line); } void error(const std::string& _message, const std::string& file = "", int line = 0){ message(ERROR, _message, file, line); } void fail(const std::string& _message, const std::string& file = "", int line = 0){ message(FAIL, _message, file, line); } // slow void flushConsole(){ // avoid slow cout during lock // copy messages to print static const uint max_messages_flush = 128; std::vector<Message> messages_copy; { std::lock_guard<std::mutex> lock(mut); messages_copy.assign(messages.begin() + numPrinted, messages.begin() + numPrinted + std::min(max_messages_flush, (uint)messages.size() - numPrinted)); } for (uint i = 0; i < messages_copy.size(); ++i){ std::cout << messageToString(messages_copy[i]) << '\n'; } std::cout.flush(); numPrinted += messages_copy.size(); } void message(int level, const std::string& messageText, const std::string& file = "", int line = 0){ #if !defined DEBUG_BUILD if (level >= DEBUG) return; #endif std::lock_guard<std::mutex> lock(mut); messages.push_back(Message{ level, messageText, file, line }); //if(autoFlush) flushConsole(); #ifdef DEBUG_BUILD if (level <= ERROR){ #ifdef _MSC_VER __debugbreak(); #endif #ifdef __GNUC__ __builtin_trap(); #endif } #endif } // reference to pointer. client should create the log himself static Log*& global(){ static Log* log = nullptr; return log; } public: Log(){ levelNames[DEBUG] = "DEBUG"; levelNames[INFO] = "INFO"; levelNames[WARNING] = "WARNING"; levelNames[ERROR] = "ERROR"; levelNames[FAIL] = "FAIL"; } ~Log(){ if (filename != ""){ std::ofstream os(filename); for (auto&m : messages){ os << messageToString(m) << '\n'; } } } //bool autoFlush = false; private: struct Message{ int level; std::string text; std::string file; int line; }; static std::string shortenPath(const std::string& s){ std::string result = s; std::string ss[] = {"include/", "include\\", "src/", "src\\"}; for(uint i=0; i<sizeof(ss)/sizeof(std::string); ++i){ auto pos = result.rfind(ss[i]); if(pos == std::string::npos) continue; result = result.substr(pos + ss[i].size(), std::string::npos); } return result; } std::string messageToString(const Message& m) const { std::string levelName; auto r = levelNames.find(m.level); if (r == levelNames.end()) levelName = std::to_string(m.level); else levelName = r->second; std::string result = levelName + ": " + m.text; if (m.file != "") result += " at " + shortenPath(m.file) + ":" + std::to_string(m.line); return result; } uint numPrinted = 0; std::vector<Message> messages; std::mutex mut; // TODO: spinlock std::unordered_map<int, std::string> levelNames; std::string filename = "atablash.log"; private: Log(const Log&) = delete; Log& operator=(const Log&) = delete; }; } inline void breakpoint(){} #ifdef NDEBUG #define DE if(0) #else // DEBUG #define DE #endif #if defined NDEBUG && not defined ASSERTS #define ASS(x) #define FLOAT_OK(x) #define ASSERT_FLOAT(x) #else #include<cassert> #define ASS(x) assert(x) #define FLOAT_OK(x) ((x) <= LDBL_MAX && (x) >= -LDBL_MAX) #define ASSERT_FLOAT(f) ASS(FLOAT_OK(f)) #endif #define DV(x) (E<#x<": "<(x)<N) #define XX E<"XX at line "<__LINE__<NL; #if defined DEBUG_BUILD or defined COLOR_CONSOLE #ifdef _WIN32 #ifndef NOMINMAX #define NOMINMAX #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include<windows.h> inline void ec(int a){static HANDLE h=GetStdHandle(-12);SetConsoleTextAttribute(h,a?12:0xf);} // color 12 inline void oc(int a){static HANDLE h=GetStdHandle(-11);SetConsoleTextAttribute(h,a?10:0xf);} // color 10 #else // *nix includes for debug #endif #else #define ec(x) #define oc(x) #endif #include <iostream> struct _E{template<class T>_E&operator<(const T&_t){DE{ec(1);std::cerr<<_t;ec(0);}return*this;}}; #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" // not working #endif static _E E; #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // E unused #ifdef __GNUC__ template<class T>void ___fhsdhsdhrtsh(){(void)E;} #endif /* #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 DEBUG_BUILD #undef FASTIO #endif #ifdef _WIN32 // TODO #ifndef NO_UNLOCKED #define NO_UNLOCKED #endif //#define fread_unlocked _fread_nolock //#define fwrite_unlocked _fwrite_nolock #endif using namespace std; using namespace __gnu_cxx; namespace ab{} using namespace ab; template<class T>inline void sortu(T& t){t.resize(std::unique(ALL(t))-t.be);} inline uint _rand(){ if(RAND_MAX < (1<<15)) return (rand()<<15) | rand(); else return rand(); } #define RND _rand() #define ri _rint() #define rui _ruint() #define rll _rll() #define rull _rull() #define rchar _rchar() #define rstr _rstr() #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 ll _rll(){ll r;cin>>r;return r;} inline char _rchar(){return cin.get();} inline string _rstr(){string s;cin>>s;return s;} template<typename T>inline void W(const T& i){cout<<i; cout.flush();} 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("%" SCNu64,&r);return r;} inline ull _rll(){ll r;scanf("%" SCNd64,&r);return r;} inline char _rchar(){return getchar();} inline string _rstr(){ string s; char c=rchar; while(c!=-1 && !isgraph(c))c=rchar; for(;;){ if(!isgraph(c))break; s+=c; c=rchar; } return s; } inline void W(char a='\n'){printf("%c",a);} inline void W(const string&s){printf("%s",s.c_str());} inline void W(int a){printf("%d",a);} inline void W(uint a){printf("%u",a);} inline void W(const ui64& a){printf("%" PRIu64,a);} inline void W(const i64& a){printf("%" PRIi64,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; FOR(i,r) _iB[i]=_iB[i+_iP]; // TODO: try memcpy int rd=FREAD(_iB+r,1,_iP,stdin); if(rd!=_iP) _iB[r+rd]=0; _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;} // unchecked! inline char _rc(){return _iB[_iP++];} inline char _rchar(){_fin(1);return _rc();} inline string _rstr(){ string s; for(;;){ char c=rchar; if(!isprint(c)||isspace(c))break; s+=c; } return s; } template<class T>inline T _rur(){ // unchecked! T __r=0;char c=_rc(); do c-='0',__r=__r*10+c,c=_rc();while(c>='0'); return __r;} template<class T>inline T _rsi(){ // unchecked! char c=_rc(); while(c<'-')c=_rc(); if(c=='-')return -_rur<T>(); else{--_iP;return _rur<T>();}} template<class T>inline T _ru(){ // unchecked! while(_rc()<'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){ // unchecked! if(numeric_limits<T>::is_signed and 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++]); while(pos<_rs); } inline void W(const char c){_fout(2);_W(c);} 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){ for(int b=0; b<l; b+=_OB){ int num = min(_OB,l-b); _fout(num); memcpy(&_oB[_oP], str+b, num); _oP+=num; } } inline void W(const char*str){W(str,strlen(str));} inline void W(const string&s){W(s.c_str(),s.siz);} 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);} #define rgraph _rgraph() inline char _rgraph(){char c;do c=rchar;while(!isgraph(c));return c;} #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)) 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=ri;return*this;} _I&operator>(uint32_t&_t){_t=rui;return*this;} _I&operator>(int64_t&_t){_t=rll;return*this;} _I&operator>(uint64_t&_t){_t=rull;return*this;} _I&operator>(char&_t){_t=rchar;return*this;} _I&operator>(string&_t){_t=rstr;return*this;} }I; inline void tc(); #ifdef GEN int argc; char **argv; int main(int _argc, char *_argv[]){ argc = _argc; argv = _argv; if(argc<2){ O < "Usage: " < argv[0] < " NR_TESTU" < N; return 1; } srand(atoi(argv[1])); #else int main(){ #endif //Log log; //log.autoFlush = true; //Log::global() = &log; #ifdef FASTIO setvbuf(stdin,0,_IONBF,0);setvbuf(stdout,0,_IONBF,0); #elif defined IOSTREAM ios_base::sync_with_stdio(0);cout.precision(10);cout.setf(ios::fixed,ios::floatfield); #if not defined DEBUG_BUILD and not defined COLOR_CONSOLE cin.tie(0); #endif #endif #ifdef DEBUG_BUILD #ifdef _WIN32 ec(0); oc(0); #else // TODO: *nix #endif #endif #ifdef READ_NUM_TEST_CASES int nz=rui;FOR(i,nz) #endif tc(); #ifdef FASTIO FWRITE(_oB,1,_oP,stdout); #endif return 0; } // END OF TEMPLATE //////////////////////////////////////////////////////////////////////////////// // // // ACTUAL SOLUTION BEGINS HERE: // // // //////////////////////////////////////////////////////////////////////////////// int n, numMachines; // reservations per machine struct Ev{ int time; bool end; int secondEnd; int iReservation; bool operator<(const Ev& o)const{ if(time != o.time) return time < o.time; if(end != o.end) return end < o.end; return secondEnd < o.secondEnd; } }; struct Machine{ vector<Ev> evs; int numSelfTriggered = 0; int numFires = 0; }; umap<int, Machine> machines; // global events struct GlobalEv{ bool endEv; int iMachine; int thisEnd; int otherEnd; int iReservation; bool operator<(const GlobalEv& o)const{ if(thisEnd != o.thisEnd) return thisEnd < o.thisEnd; if(endEv != o.endEv) return endEv < o.endEv; return otherEnd < o.otherEnd; } }; vector<GlobalEv> globalEvs; int resultFires = 0; struct Reservation{ //int fr,to; int result = INT_MAX; int machine; }; // indexed by iReservation vector<Reservation> reservations; struct AN{ int koniec; int poczatek; int iReservation; bool operator<(const AN& o)const{ if(koniec != o.koniec) return koniec < o.koniec; return poczatek < o.poczatek; } }; umap<int,multiset<AN>> active; void process(){ E < NL < "Process" < NL; sort(globalEvs.be, globalEvs.en); FOR(i, globalEvs.size()){ auto& ev = globalEvs[i]; if(ev.endEv) E < "END event at " < ev.thisEnd < NL; else E < "BEGIN event at " < ev.thisEnd < NL; // self trigger if(ev.endEv){ ++machines[ev.iMachine].numSelfTriggered; } if(ev.endEv and machines[ev.iMachine].numSelfTriggered > machines[ev.iMachine].numFires){ // fire! ++resultFires; E < "fire at " < ev.thisEnd < " to satisfy reservation " < ev.iReservation < NL; vector<int> toErase; for(auto& itr : active){ auto& secik = itr.se; int iRes = secik.begin()->iReservation; E < "satisfied reservation " < iRes < NL; reservations[iRes].result = ev.thisEnd; int iMachine = reservations[iRes].machine; ++machines[iMachine].numFires; secik.erase(secik.begin()); if(secik.empty()) toErase.pub(itr.fi); } for(auto x : toErase) active.erase(x); } else if(!ev.endEv){ // startEv active[ev.iMachine].insert({ev.otherEnd, ev.thisEnd, ev.iReservation}); } } } struct FB{ int time; int secondEnd; int iReservation; bool operator<(const FB& o)const{ return secondEnd > o.secondEnd; } }; // process each machine bool processMachines(){ for(auto& entry : machines){ E < NL < "Process machine " < entry.fi < NL; auto& vec = entry.se.evs; sort(vec.be, vec.en); multiset<FB> firesBehind; int nextFireAllowed = vec.back().time; int numBegins = 0; int totalFires = 0; OF(i,0,vec.siz){ int time = vec[i].time; bool end = vec[i].end; int secondEnd = vec[i].secondEnd; if(end) E < "END at " < time < NL; else E < "BEGIN at " < time < NL; if(!firesBehind.empty()) ASS(nextFireAllowed == time); nextFireAllowed = time; if(end){ firesBehind.insert({time, secondEnd, vec[i].iReservation}); } if(!end){ ++numBegins; if(numBegins > totalFires + 1){ return false; } } int nextTime = -INT_MAX; if(i-1 >= 0) nextTime = vec[i-1].time; // do until nextTime while(!firesBehind.empty() and nextFireAllowed > nextTime){ globalEvs.pub({true, entry.fi, nextFireAllowed, firesBehind.begin()->secondEnd, firesBehind.begin()->iReservation}); globalEvs.pub({false, entry.fi, firesBehind.begin()->secondEnd, time, firesBehind.begin()->iReservation}); ++totalFires; E < "fire at " < nextFireAllowed < "; reservation from " < firesBehind.begin()->secondEnd < NL; firesBehind.erase(firesBehind.begin()); --nextFireAllowed; } } ASS(firesBehind.empty()); } return true; } inline void tc(){ I > n > numMachines; reservations.resize(n); FOR(i,n){ int fr = ri; int to = ri; int iMachine = ri-1; //swap(fr,to); //fr = -fr; //to = -to; machines[iMachine].evs.pub({fr,false,to,i}); machines[iMachine].evs.pub({to,true,fr,i}); reservations[i].machine = iMachine; } // process each machine bool r = processMachines(); if(!r){ O < "NIE" < NL; return; } process(); O < resultFires < NL; FOR(i,n){ O < reservations[i].result < NL; } }
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 | //#define READ_NUM_TEST_CASES //#define ASSERTS // force asserts on online judge #define FASTIO //#include<atablash/splay/common.hpp> //#include<atablash/splay/node.hpp> //#include<atablash/interval-tree.hpp> //#include<atablash/hash.hpp> //typedef H1<1000000007> H; //////////////////////////////////////////////////////////////////////////////// // // // ACTUAL 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 // PRIi64, PRIui64 #define __STDC_FORMAT_MACROS #include<inttypes.h> //#include<type_traits> #define _CAT(a,b) a##b #define CAT(a,b) _CAT(a,b) #define _10TH(a,b,c,d,e,f,g,h,i,X,...) X #define VA_CNT(...) _10TH(__VA_ARGS__,9,8,7,6,5,4,3,2,1,0) #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,0) #define VA_GTONE(a,...) CAT(a,_VA_GTONE(__VA_ARGS__))(__VA_ARGS__) #define MIN_GCC(a,b,c) (__GNUC__ > (a) || \ (__GNUC__ == (a) && (__GNUC_MINOR__ > (b) || \ (__GNUC_MINOR__ == (b) && \ __GNUC_PATCHLEVEL__ >= (c))))) // TODO: po co to bylo?? /* #include<functional> #if __cplusplus >= 201103L namespace std { template<class T> struct hash { typedef T argument_type; typedef typename std::underlying_type< argument_type >::type underlying_type; typedef typename std::hash< underlying_type >::result_type result_type; result_type operator()( const argument_type& arg ) const { std::hash< underlying_type > hasher; return hasher( static_cast< underlying_type >( arg ) ); } }; } #endif */ #define bac back() #define fro front() #define emp empty() #define fi first #define se second #define siz size() #define ins insert #define era erase #define mp make_pair #define be begin() #define en end() #define rbe rbegin() #define ren rend() #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 pq priority_queue #define si (int) #undef FO #undef OF #define FOR(i,n) for(int i=0; i<(int)(n); ++i) #define FO(i,a,b) for(int i=(a); i<(int)(b); ++i) #define OF(i,a,b) for(int i=(int)(b)-1;i>=(int)(a);--i) #define FE(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it) #define FER(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ) #define ALL(c) (c).begin(),(c).end() #define ZERO(c) memset(c,0,sizeof(c)) #define AU(v,val) __typeof(val) v(val) const char NL='\n'; const char SP=' '; #include<stdint.h> #include<utility> #include<vector> #include<memory> // abbrevs typedef unsigned int uint; 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 std::pair<double,double> pdd; typedef std::vector<i32> vi; #define VE std::vector #define umap std::unordered_map #define umultimap std::unordered_multimap #define uset std::unordered_set #define umultiset std::unordered_multiset typedef unsigned short ushort; typedef unsigned char uchar; template<class T> using sptr = std::shared_ptr<T>; template<class T> using uptr = std::unique_ptr<T>; template<class A, class B> using p = std::pair<A, B>; namespace ab{ struct Void {}; // convert to float with enough precision 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;}; // get type capable of storing multiplication result 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__ && ( defined __x86_64__ || defined __ppc64__ || defined __MINGW64__ ) typedef __int128_t i128; typedef __uint128_t ui128; template<>struct Double<i64>{typedef i128 R;}; template<>struct Double<ui64>{typedef ui128 R;}; #endif } // Visual C++ intristics #ifdef _MSC_VER #include <intrin.h> #define __builtin_popcount __popcnt #ifdef _WIN64 #define __builtin_popcountll __popcnt64 #else inline int __builtin_popcountll(__int64 a){ return __builtin_popcount((ui32)a) + __builtin_popcount(a >> 32); } #endif #endif // Visual C++ 'and', 'or', 'not' #ifdef _MSC_VER #define and && #define or || #define not ! #endif namespace ab{ template<class T>inline T cbitl(T x,int i){return (x<<i) ^ (x>>(sizeof(T)*8-i));} // cycle bits left inline int popcount(uint i){return __builtin_popcount(i);} inline int popcount(ull i){return __builtin_popcountll(i);} #ifdef __GNUC__ inline int parity(uint i){return __builtin_parity(i);} inline int parity(ull i){return __builtin_parityll(i);} inline int ilog2(uint i){return 31-__builtin_clz(i);} // int log; floor(log2(i)) inline int ilog2(ull i){return 63-__builtin_clzll(i);} #endif template<class T>inline bool isPowerOf2(const T&x){return !(x&(x-1));} struct Static{ Static() = default; Static(const Static&) = delete; Static(Static&&) = delete; Static(const Static&&) = delete; Static& operator=(const Static&) = delete; Static& operator=(Static&&) = delete; Static& operator=(const Static&&) = delete; }; } //#if MIN_GCC(4,1,3) //#include<bits/stdc++.h> //#else #include<vector> #include<map> #include<queue> #include<algorithm> #include<string> #include<stdint.h> #include<cstring> #include<iostream> #include<set> #include<climits> #include<bitset> #include<limits> #include<sstream> #include<cmath> //#endif // enable debug if any debug macro is defined #if (defined _DEBUG || defined DEBUG) && !defined DEBUG_BUILD #define DEBUG_BUILD #endif // DEBUG_BUILD (set or not set) overrides NDEBUG #ifdef DEBUG_BUILD #undef NDEBUG //#pragma message "Compiling in DEBUG mode." #else #ifndef NDEBUG #define NDEBUG #endif #endif //#include <cstdio> //#include <cfloat> #include<vector> #include<unordered_map> // ? #include<iostream> #include<fstream> #include<string> #include<algorithm> #include<mutex> // to_string fix for MinGW #include<map> #include<iostream> #if __cplusplus >= 201103L or defined _MSC_VER #include <unordered_map> #include <unordered_set> namespace std{ #else #include <ext/hash_map> #include <ext/hash_set> namespace __gnu_cxx{ #define unordered_map hash_map #define unordered_multimap hash_multimap #define unordered_set hash_set #define unordered_multiset hash_multiset /* template<class K, class V> class unordered_map : public hash_map<K,V>{ public: typename hash_map<K,V>::iterator erase(const typename hash_map<K,V>::iterator& it){ typename hash_map<K,V>::iterator r = it; ++r; if(r!=hash_map<K,V>::end()){ K key = r->first; hash_map<K,V>::erase(it); return hash_map<K,V>::find(key); } else{ hash_map<K,V>::erase(it); return r; } } typename hash_map<K,V>::size_type erase(const K& key){ return hash_map<K,V>::erase(key); } }; */ #endif // 1,2,last (!!!!!) /*template<>*/ template<class A,class B>struct hash<std::map<A,B> >{ size_t operator()(const std::map<A,B>& m) const{ size_t r = m.size(); if(!r)return 0; __typeof(m.begin()) i=m.be; r^=hash<__typeof(i)>()(i); ++i; r^=cbitl(hash<__typeof(i)>()(*i),sizeof(r)*8/4); i=m.end(); --i; r^=cbitl(hash<__typeof(i)>()(*i),sizeof(r)*8/2); return r; } }; // hash pairs: /*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) ^ ab::cbitl(hash<B>()(p.second),sizeof(size_t)*8/2); } }; // hash enums: // // TODO: fix for msvc #if defined __GNUC__ and MIN_GCC(4,8,4) template<class E> struct hash { using sfinae = typename std::enable_if<std::is_enum<E>::value, E>::type; public: size_t operator()(const E&e) const { return std::hash<typename std::underlying_type<E>::type>()((typename std::underlying_type<E>::type)e); } }; #endif } // namespace std / __gnu_cxx // component-wise pair operators template<class A, class B, class C, class D> inline std::pair<A,B>& operator+=(std::pair<A,B>& p, const std::pair<C,D>& o){ p.first+=o.first; p.second+=o.second; return p; } template<class A, class B, class C, class D> inline std::pair<A,B>& operator-=(std::pair<A,B>& p, const std::pair<C,D>& o){ p.first-=o.first; p.second-=o.second; return p; } template<class A, class B, class C, class D> inline std::pair<A,B>& operator*=(std::pair<A,B>& p, const std::pair<C,D>& o){ p.first*=o.first; p.second*=o.second; return p; } template<class A, class B, class C, class D> inline std::pair<A,B>& operator/=(std::pair<A,B>& p, const std::pair<C,D>& o){ p.first/=o.first; p.second/=o.second; return p; } template<class Afi, class Ase, class Bfi, class Bse> inline std::pair<decltype(Afi() + Bfi()), decltype(Ase() + Bse())>& operator+(const std::pair<Afi,Ase>& a, const std::pair<Bfi,Bse>& b){ return std::make_pair(a.fi+b.fi, a.se+b.se); } template<class Afi, class Ase, class Bfi, class Bse> inline std::pair<decltype(Afi() - Bfi()), decltype(Ase() - Bse())>& operator-(const std::pair<Afi,Ase>& a, const std::pair<Bfi,Bse>& b){ return std::make_pair(a.fi-b.fi, a.se-b.se); } template<class Afi, class Ase, class Bfi, class Bse> inline std::pair<decltype(Afi()*Bfi()), decltype(Ase()*Bse())>& operator*(const std::pair<Afi,Ase>& a, const std::pair<Bfi,Bse>& b){ return std::make_pair(a.fi*b.fi, a.se*b.se); } template<class Afi, class Ase, class Bfi, class Bse> inline std::pair<decltype(Afi() / Bfi()), decltype(Ase() / Bse())>& operator/(const std::pair<Afi,Ase>& a, const std::pair<Bfi,Bse>& b){ return std::make_pair(a.fi/b.fi, a.se/b.se); } // vector operators template<class T, class U> inline std::vector<T>& operator+=(std::vector<T>& v, const std::vector<U>& o){ ASS(v.siz == o.siz); FOR(i,v.siz) v[i] += o[i]; return v; } template<class T> inline std::vector<T>& operator*=(std::vector<T>& v, const T& a){ FOR(i,v.siz) v[i] *= a; return v; } // serialization template<class A,class B>inline std::ostream&operator<<(std::ostream&o,const std::pair<A,B>&p){o<<'<'<<p.first<<", "<<p.second<<'>';return o;} template<class A,class B>inline std::ostream&operator<<(std::ostream&o,const std::map<A,B>&m){o<<'\n';FE(k,m)o<<"map["<<k->first<<"] -> "<<k->se<<'\n';return o;} template<class A,class B>inline std::ostream&operator<<(std::ostream&o,const umap<A,B>&m){o<<'\n';FE(k,m)o<<"umap["<<k->first<<"] -> "<<k->se<<'\n';return o;} template<class A,class B>inline std::ostream&operator<<(std::ostream&o,const uset<A,B>&_m){o<<"uset{\n";FE(k,_m)o<<*k<<'\n';o<<'\n';return o;} template<class A>inline std::ostream&operator<<(std::ostream&o,const std::vector<A>&_v){o<<'\n';FOR(i,_v.siz)o<<"vector["<<i<<"] = "<<_v[i]<<"}\n";return o;} // fix for MinGW: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52015 #ifdef _GLIBCXX_HAVE_BROKEN_VSWPRINTF namespace std{ template<class T> inline string to_string(const T& t){ stringstream ss; ss << t; return ss.str(); } } #endif //#define LOG0(str) fprintf(stderr,"%s:%d - " str "\n",__FILE__,__LINE__) //#define LOG1(str,...) fprintf(stderr,"%s:%d - " str "\n",__FILE__,__LINE__,__VA_ARGS__) //#define LOG(...) VA_GTONE(LOG,__VA_ARGS__) #define LOGD(str) if(ab::Log::global()) ab::Log::global()->debug(str,__FILE__,__LINE__) #define LOGI(str) if(ab::Log::global()) ab::Log::global()->info(str,__FILE__,__LINE__) #define LOGW(str) if(ab::Log::global()) ab::Log::global()->warning(str,__FILE__,__LINE__) #define LOGE(str) if(ab::Log::global()) ab::Log::global()->error(str,__FILE__,__LINE__) #define LOGF(str) if(ab::Log::global()) ab::Log::global()->fail(str,__FILE__,__LINE__) namespace ab{ // TODO: czas logowania // TODO: interfejs do dodawania nazw message levelom, ustawiania nazwy pliku z logiem, czy printowac na stderr, ... // // level >= DEBUG powoduje ignorowanie logowania w release class Log{ public: enum{ DEBUG = 5000, INFO = 4000, // default? WARNING = 3000, ERROR = 2000, FAIL = 1000}; public: void debug(const std::string& _message, const std::string& file="", int line=0){ message(DEBUG, _message, file, line); } void info(const std::string& _message, const std::string& file = "", int line = 0){ message(INFO, _message, file, line); } void warning(const std::string& _message, const std::string& file = "", int line = 0){ message(WARNING, _message, file, line); } void error(const std::string& _message, const std::string& file = "", int line = 0){ message(ERROR, _message, file, line); } void fail(const std::string& _message, const std::string& file = "", int line = 0){ message(FAIL, _message, file, line); } // slow void flushConsole(){ // avoid slow cout during lock // copy messages to print static const uint max_messages_flush = 128; std::vector<Message> messages_copy; { std::lock_guard<std::mutex> lock(mut); messages_copy.assign(messages.begin() + numPrinted, messages.begin() + numPrinted + std::min(max_messages_flush, (uint)messages.size() - numPrinted)); } for (uint i = 0; i < messages_copy.size(); ++i){ std::cout << messageToString(messages_copy[i]) << '\n'; } std::cout.flush(); numPrinted += messages_copy.size(); } void message(int level, const std::string& messageText, const std::string& file = "", int line = 0){ #if !defined DEBUG_BUILD if (level >= DEBUG) return; #endif std::lock_guard<std::mutex> lock(mut); messages.push_back(Message{ level, messageText, file, line }); //if(autoFlush) flushConsole(); #ifdef DEBUG_BUILD if (level <= ERROR){ #ifdef _MSC_VER __debugbreak(); #endif #ifdef __GNUC__ __builtin_trap(); #endif } #endif } // reference to pointer. client should create the log himself static Log*& global(){ static Log* log = nullptr; return log; } public: Log(){ levelNames[DEBUG] = "DEBUG"; levelNames[INFO] = "INFO"; levelNames[WARNING] = "WARNING"; levelNames[ERROR] = "ERROR"; levelNames[FAIL] = "FAIL"; } ~Log(){ if (filename != ""){ std::ofstream os(filename); for (auto&m : messages){ os << messageToString(m) << '\n'; } } } //bool autoFlush = false; private: struct Message{ int level; std::string text; std::string file; int line; }; static std::string shortenPath(const std::string& s){ std::string result = s; std::string ss[] = {"include/", "include\\", "src/", "src\\"}; for(uint i=0; i<sizeof(ss)/sizeof(std::string); ++i){ auto pos = result.rfind(ss[i]); if(pos == std::string::npos) continue; result = result.substr(pos + ss[i].size(), std::string::npos); } return result; } std::string messageToString(const Message& m) const { std::string levelName; auto r = levelNames.find(m.level); if (r == levelNames.end()) levelName = std::to_string(m.level); else levelName = r->second; std::string result = levelName + ": " + m.text; if (m.file != "") result += " at " + shortenPath(m.file) + ":" + std::to_string(m.line); return result; } uint numPrinted = 0; std::vector<Message> messages; std::mutex mut; // TODO: spinlock std::unordered_map<int, std::string> levelNames; std::string filename = "atablash.log"; private: Log(const Log&) = delete; Log& operator=(const Log&) = delete; }; } inline void breakpoint(){} #ifdef NDEBUG #define DE if(0) #else // DEBUG #define DE #endif #if defined NDEBUG && not defined ASSERTS #define ASS(x) #define FLOAT_OK(x) #define ASSERT_FLOAT(x) #else #include<cassert> #define ASS(x) assert(x) #define FLOAT_OK(x) ((x) <= LDBL_MAX && (x) >= -LDBL_MAX) #define ASSERT_FLOAT(f) ASS(FLOAT_OK(f)) #endif #define DV(x) (E<#x<": "<(x)<N) #define XX E<"XX at line "<__LINE__<NL; #if defined DEBUG_BUILD or defined COLOR_CONSOLE #ifdef _WIN32 #ifndef NOMINMAX #define NOMINMAX #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include<windows.h> inline void ec(int a){static HANDLE h=GetStdHandle(-12);SetConsoleTextAttribute(h,a?12:0xf);} // color 12 inline void oc(int a){static HANDLE h=GetStdHandle(-11);SetConsoleTextAttribute(h,a?10:0xf);} // color 10 #else // *nix includes for debug #endif #else #define ec(x) #define oc(x) #endif #include <iostream> struct _E{template<class T>_E&operator<(const T&_t){DE{ec(1);std::cerr<<_t;ec(0);}return*this;}}; #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-variable" // not working #endif static _E E; #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // E unused #ifdef __GNUC__ template<class T>void ___fhsdhsdhrtsh(){(void)E;} #endif /* #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 DEBUG_BUILD #undef FASTIO #endif #ifdef _WIN32 // TODO #ifndef NO_UNLOCKED #define NO_UNLOCKED #endif //#define fread_unlocked _fread_nolock //#define fwrite_unlocked _fwrite_nolock #endif using namespace std; using namespace __gnu_cxx; namespace ab{} using namespace ab; template<class T>inline void sortu(T& t){t.resize(std::unique(ALL(t))-t.be);} inline uint _rand(){ if(RAND_MAX < (1<<15)) return (rand()<<15) | rand(); else return rand(); } #define RND _rand() #define ri _rint() #define rui _ruint() #define rll _rll() #define rull _rull() #define rchar _rchar() #define rstr _rstr() #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 ll _rll(){ll r;cin>>r;return r;} inline char _rchar(){return cin.get();} inline string _rstr(){string s;cin>>s;return s;} template<typename T>inline void W(const T& i){cout<<i; cout.flush();} 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("%" SCNu64,&r);return r;} inline ull _rll(){ll r;scanf("%" SCNd64,&r);return r;} inline char _rchar(){return getchar();} inline string _rstr(){ string s; char c=rchar; while(c!=-1 && !isgraph(c))c=rchar; for(;;){ if(!isgraph(c))break; s+=c; c=rchar; } return s; } inline void W(char a='\n'){printf("%c",a);} inline void W(const string&s){printf("%s",s.c_str());} inline void W(int a){printf("%d",a);} inline void W(uint a){printf("%u",a);} inline void W(const ui64& a){printf("%" PRIu64,a);} inline void W(const i64& a){printf("%" PRIi64,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; FOR(i,r) _iB[i]=_iB[i+_iP]; // TODO: try memcpy int rd=FREAD(_iB+r,1,_iP,stdin); if(rd!=_iP) _iB[r+rd]=0; _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;} // unchecked! inline char _rc(){return _iB[_iP++];} inline char _rchar(){_fin(1);return _rc();} inline string _rstr(){ string s; for(;;){ char c=rchar; if(!isprint(c)||isspace(c))break; s+=c; } return s; } template<class T>inline T _rur(){ // unchecked! T __r=0;char c=_rc(); do c-='0',__r=__r*10+c,c=_rc();while(c>='0'); return __r;} template<class T>inline T _rsi(){ // unchecked! char c=_rc(); while(c<'-')c=_rc(); if(c=='-')return -_rur<T>(); else{--_iP;return _rur<T>();}} template<class T>inline T _ru(){ // unchecked! while(_rc()<'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){ // unchecked! if(numeric_limits<T>::is_signed and 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++]); while(pos<_rs); } inline void W(const char c){_fout(2);_W(c);} 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){ for(int b=0; b<l; b+=_OB){ int num = min(_OB,l-b); _fout(num); memcpy(&_oB[_oP], str+b, num); _oP+=num; } } inline void W(const char*str){W(str,strlen(str));} inline void W(const string&s){W(s.c_str(),s.siz);} 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);} #define rgraph _rgraph() inline char _rgraph(){char c;do c=rchar;while(!isgraph(c));return c;} #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)) 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=ri;return*this;} _I&operator>(uint32_t&_t){_t=rui;return*this;} _I&operator>(int64_t&_t){_t=rll;return*this;} _I&operator>(uint64_t&_t){_t=rull;return*this;} _I&operator>(char&_t){_t=rchar;return*this;} _I&operator>(string&_t){_t=rstr;return*this;} }I; inline void tc(); #ifdef GEN int argc; char **argv; int main(int _argc, char *_argv[]){ argc = _argc; argv = _argv; if(argc<2){ O < "Usage: " < argv[0] < " NR_TESTU" < N; return 1; } srand(atoi(argv[1])); #else int main(){ #endif //Log log; //log.autoFlush = true; //Log::global() = &log; #ifdef FASTIO setvbuf(stdin,0,_IONBF,0);setvbuf(stdout,0,_IONBF,0); #elif defined IOSTREAM ios_base::sync_with_stdio(0);cout.precision(10);cout.setf(ios::fixed,ios::floatfield); #if not defined DEBUG_BUILD and not defined COLOR_CONSOLE cin.tie(0); #endif #endif #ifdef DEBUG_BUILD #ifdef _WIN32 ec(0); oc(0); #else // TODO: *nix #endif #endif #ifdef READ_NUM_TEST_CASES int nz=rui;FOR(i,nz) #endif tc(); #ifdef FASTIO FWRITE(_oB,1,_oP,stdout); #endif return 0; } // END OF TEMPLATE //////////////////////////////////////////////////////////////////////////////// // // // ACTUAL SOLUTION BEGINS HERE: // // // //////////////////////////////////////////////////////////////////////////////// int n, numMachines; // reservations per machine struct Ev{ int time; bool end; int secondEnd; int iReservation; bool operator<(const Ev& o)const{ if(time != o.time) return time < o.time; if(end != o.end) return end < o.end; return secondEnd < o.secondEnd; } }; struct Machine{ vector<Ev> evs; int numSelfTriggered = 0; int numFires = 0; }; umap<int, Machine> machines; // global events struct GlobalEv{ bool endEv; int iMachine; int thisEnd; int otherEnd; int iReservation; bool operator<(const GlobalEv& o)const{ if(thisEnd != o.thisEnd) return thisEnd < o.thisEnd; if(endEv != o.endEv) return endEv < o.endEv; return otherEnd < o.otherEnd; } }; vector<GlobalEv> globalEvs; int resultFires = 0; struct Reservation{ //int fr,to; int result = INT_MAX; int machine; }; // indexed by iReservation vector<Reservation> reservations; struct AN{ int koniec; int poczatek; int iReservation; bool operator<(const AN& o)const{ if(koniec != o.koniec) return koniec < o.koniec; return poczatek < o.poczatek; } }; umap<int,multiset<AN>> active; void process(){ E < NL < "Process" < NL; sort(globalEvs.be, globalEvs.en); FOR(i, globalEvs.size()){ auto& ev = globalEvs[i]; if(ev.endEv) E < "END event at " < ev.thisEnd < NL; else E < "BEGIN event at " < ev.thisEnd < NL; // self trigger if(ev.endEv){ ++machines[ev.iMachine].numSelfTriggered; } if(ev.endEv and machines[ev.iMachine].numSelfTriggered > machines[ev.iMachine].numFires){ // fire! ++resultFires; E < "fire at " < ev.thisEnd < " to satisfy reservation " < ev.iReservation < NL; vector<int> toErase; for(auto& itr : active){ auto& secik = itr.se; int iRes = secik.begin()->iReservation; E < "satisfied reservation " < iRes < NL; reservations[iRes].result = ev.thisEnd; int iMachine = reservations[iRes].machine; ++machines[iMachine].numFires; secik.erase(secik.begin()); if(secik.empty()) toErase.pub(itr.fi); } for(auto x : toErase) active.erase(x); } else if(!ev.endEv){ // startEv active[ev.iMachine].insert({ev.otherEnd, ev.thisEnd, ev.iReservation}); } } } struct FB{ int time; int secondEnd; int iReservation; bool operator<(const FB& o)const{ return secondEnd > o.secondEnd; } }; // process each machine bool processMachines(){ for(auto& entry : machines){ E < NL < "Process machine " < entry.fi < NL; auto& vec = entry.se.evs; sort(vec.be, vec.en); multiset<FB> firesBehind; int nextFireAllowed = vec.back().time; int numBegins = 0; int totalFires = 0; OF(i,0,vec.siz){ int time = vec[i].time; bool end = vec[i].end; int secondEnd = vec[i].secondEnd; if(end) E < "END at " < time < NL; else E < "BEGIN at " < time < NL; if(!firesBehind.empty()) ASS(nextFireAllowed == time); nextFireAllowed = time; if(end){ firesBehind.insert({time, secondEnd, vec[i].iReservation}); } if(!end){ ++numBegins; if(numBegins > totalFires + 1){ return false; } } int nextTime = -INT_MAX; if(i-1 >= 0) nextTime = vec[i-1].time; // do until nextTime while(!firesBehind.empty() and nextFireAllowed > nextTime){ globalEvs.pub({true, entry.fi, nextFireAllowed, firesBehind.begin()->secondEnd, firesBehind.begin()->iReservation}); globalEvs.pub({false, entry.fi, firesBehind.begin()->secondEnd, time, firesBehind.begin()->iReservation}); ++totalFires; E < "fire at " < nextFireAllowed < "; reservation from " < firesBehind.begin()->secondEnd < NL; firesBehind.erase(firesBehind.begin()); --nextFireAllowed; } } ASS(firesBehind.empty()); } return true; } inline void tc(){ I > n > numMachines; reservations.resize(n); FOR(i,n){ int fr = ri; int to = ri; int iMachine = ri-1; //swap(fr,to); //fr = -fr; //to = -to; machines[iMachine].evs.pub({fr,false,to,i}); machines[iMachine].evs.pub({to,true,fr,i}); reservations[i].machine = iMachine; } // process each machine bool r = processMachines(); if(!r){ O < "NIE" < NL; return; } process(); O < resultFires < NL; FOR(i,n){ O < reservations[i].result < NL; } } |