testlib.h 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072
  1. /*
  2. * It is strictly recommended to include "testlib.h" before any other include
  3. * in your code. In this case testlib overrides compiler specific "random()".
  4. *
  5. * If you can't compile your code and compiler outputs something about
  6. * ambiguous call of "random_shuffle", "rand" or "srand" it means that
  7. * you shouldn't use them. Use "shuffle", and "rnd.next()" instead of them
  8. * because these calls produce stable result for any C++ compiler. Read
  9. * sample generator sources for clarification.
  10. *
  11. * Please read the documentation for class "random_t" and use "rnd" instance in
  12. * generators. Probably, these sample calls will be usefull for you:
  13. * rnd.next(); rnd.next(100); rnd.next(1, 2);
  14. * rnd.next(3.14); rnd.next("[a-z]{1,100}").
  15. *
  16. * Also read about wnext() to generate off-center random distribution.
  17. *
  18. * See http://code.google.com/p/testlib/ to get latest version or bug tracker.
  19. */
  20. #ifndef _TESTLIB_H_
  21. #define _TESTLIB_H_
  22. /*
  23. * Copyright (c) 2005-2013
  24. */
  25. #define VERSION "0.8.8"
  26. /*
  27. * Mike Mirzayanov
  28. *
  29. * This material is provided "as is", with absolutely no warranty expressed
  30. * or implied. Any use is at your own risk.
  31. *
  32. * Permission to use or copy this software for any purpose is hereby granted
  33. * without fee, provided the above notices are retained on all copies.
  34. * Permission to modify the code and to distribute modified code is granted,
  35. * provided the above notices are retained, and a notice that the code was
  36. * modified is included with the above copyright notice.
  37. *
  38. */
  39. /* NOTE: This file contains testlib library for C++.
  40. *
  41. * Check, using testlib running format:
  42. * check.exe <Input_File> <Output_File> <Answer_File> [<Result_File> [-appes]],
  43. * If result file is specified it will contain results.
  44. *
  45. * Validator, using testlib running format:
  46. * validator.exe < input.txt,
  47. * It will return non-zero exit code and writes message to standard output.
  48. *
  49. * Generator, using testlib running format:
  50. * gen.exe [parameter-1] [parameter-2] [... paramerter-n]
  51. * You can write generated test(s) into standard output or into the file(s).
  52. *
  53. * Interactor, using testlib running format:
  54. * interactor.exe <Input_File> <Output_File> [<Answer_File> [<Result_File> [-appes]]],
  55. * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2],
  56. * can be judged by checker later), reads program output from ouf (mapped to stdin),
  57. * writes output to program via stdout (use cout, printf, etc).
  58. */
  59. const char* latestFeatures[] = {
  60. "Added attribute 'points' to the XML output in case of result=_points",
  61. "Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14",
  62. "Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading",
  63. "Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()",
  64. "Manual buffer in InStreams, some IO speed improvements",
  65. "Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true",
  66. "Introduced guard against missed quitf() in checker or readEof() in validators",
  67. "Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers",
  68. "Supported registerInteraction(argc, argv)",
  69. "Print checker message to the stderr instead of stdout",
  70. "Supported TResult _points to output calculated score, use quitp(...) functions",
  71. "Fixed to be compilable on Mac",
  72. "PC_BASE_EXIT_CODE=50 in case of defined TESTSYS",
  73. "Fixed issues 19-21, added __attribute__ format printf",
  74. "Some bug fixes",
  75. "ouf.readInt(1, 100) and similar calls return WA",
  76. "Modified random_t to avoid integer overflow",
  77. "Truncated checker output [patch by Stepan Gatilov]",
  78. "Renamed class random -> class random_t",
  79. "Supported name parameter for read-and-validation methods, like readInt(1, 2, \"n\")",
  80. "Fixed bug in readDouble()",
  81. "Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()",
  82. "Supported \"partially correct\", example: quitf(_pc(13), \"result=%d\", result)",
  83. "Added shuffle(begin, end), use it instead of random_shuffle(begin, end)",
  84. "Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode",
  85. "Package extended with samples of generators and validators",
  86. "Written the documentation for classes and public methods in testlib.h",
  87. "Implemented random routine to support generators, use registerGen() to switch it on",
  88. "Implemented strict mode to validate tests, use registerValidation() to switch it on",
  89. "Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output",
  90. "Added InStream::readLong() and removed InStream::readLongint()",
  91. "Now no footer added to each report by default (use directive FOOTER to switch on)",
  92. "Now every checker has a name, use setName(const char* format, ...) to set it",
  93. "Now it is compatible with TTS (by Kittens Computing)",
  94. "Added \'ensure(condition, message = \"\")\' feature, it works like assert()",
  95. "Fixed compatibility with MS C++ 7.1",
  96. "Added footer with exit code information",
  97. "Added compatibility with EJUDGE (compile with EJUDGE directive)"
  98. };
  99. #ifdef _MSC_VER
  100. #define _CRT_SECURE_NO_DEPRECATE
  101. #define _CRT_SECURE_NO_WARNINGS
  102. #endif
  103. /* Overrides random() for Borland C++. */
  104. #define random __random_deprecated
  105. #include <stdlib.h>
  106. #include <cstdlib>
  107. #include <climits>
  108. #include <algorithm>
  109. #undef random
  110. #include <cstdio>
  111. #include <cctype>
  112. #include <string>
  113. #include <vector>
  114. #include <cmath>
  115. #include <sstream>
  116. #include <fstream>
  117. #include <cstring>
  118. #include <limits>
  119. #include <stdarg.h>
  120. #include <fcntl.h>
  121. #if ( _WIN32 || __WIN32__ || _WIN64 || __WIN64__ )
  122. # if !defined(_MSC_VER) || _MSC_VER>1400
  123. # include <windows.h>
  124. # else
  125. # define WORD unsigned short
  126. # endif
  127. # include <io.h>
  128. # define ON_WINDOWS
  129. #else
  130. # define WORD unsigned short
  131. #endif
  132. #ifndef LLONG_MIN
  133. #define LLONG_MIN (-9223372036854775807LL - 1)
  134. #endif
  135. #define LF ((char)10)
  136. #define CR ((char)13)
  137. #define TAB ((char)9)
  138. #define SPACE ((char)' ')
  139. #define EOFC ((char)26)
  140. #ifndef OK_EXIT_CODE
  141. # define OK_EXIT_CODE 0
  142. #endif
  143. #ifndef WA_EXIT_CODE
  144. # ifdef EJUDGE
  145. # define WA_EXIT_CODE 5
  146. # else
  147. # define WA_EXIT_CODE 1
  148. # endif
  149. #endif
  150. #ifndef PE_EXIT_CODE
  151. # ifdef EJUDGE
  152. # define PE_EXIT_CODE 4
  153. # else
  154. # define PE_EXIT_CODE 2
  155. # endif
  156. #endif
  157. #ifndef FAIL_EXIT_CODE
  158. # ifdef EJUDGE
  159. # define FAIL_EXIT_CODE 6
  160. # else
  161. # define FAIL_EXIT_CODE 3
  162. # endif
  163. #endif
  164. #ifndef DIRT_EXIT_CODE
  165. # ifdef EJUDGE
  166. # define DIRT_EXIT_CODE 6
  167. # else
  168. # define DIRT_EXIT_CODE 4
  169. # endif
  170. #endif
  171. #ifndef POINTS_EXIT_CODE
  172. # define POINTS_EXIT_CODE 0
  173. #endif
  174. #ifndef PC_BASE_EXIT_CODE
  175. # ifdef TESTSYS
  176. # define PC_BASE_EXIT_CODE 50
  177. # else
  178. # define PC_BASE_EXIT_CODE 0
  179. # endif
  180. #endif
  181. #define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[((condition) != 0) * 2 - 1];
  182. #ifdef ON_WINDOWS
  183. #define I64 "%I64d"
  184. #define U64 "%I64u"
  185. #else
  186. #define I64 "%lld"
  187. #define U64 "%llu"
  188. #endif
  189. #ifdef _MSC_VER
  190. # define NORETURN __declspec(noreturn)
  191. #else
  192. # define NORETURN
  193. #endif
  194. static char __testlib_format_buffer[16777216];
  195. static int __testlib_format_buffer_usage_count = 0;
  196. #define FMT_TO_RESULT(fmt, cstr, result) std::string result; \
  197. if (__testlib_format_buffer_usage_count != 0) \
  198. __testlib_fail("FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0"); \
  199. __testlib_format_buffer_usage_count++; \
  200. va_list ap; \
  201. va_start(ap, fmt); \
  202. std::vsprintf(__testlib_format_buffer, cstr, ap); \
  203. va_end(ap); \
  204. result = std::string(__testlib_format_buffer); \
  205. __testlib_format_buffer_usage_count--; \
  206. const long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;
  207. template<typename T>
  208. static inline T __testlib_abs(const T& x)
  209. {
  210. return x > 0 ? x : -x;
  211. }
  212. template<typename T>
  213. static inline T __testlib_min(const T& a, const T& b)
  214. {
  215. return a < b ? a : b;
  216. }
  217. template<typename T>
  218. static inline T __testlib_max(const T& a, const T& b)
  219. {
  220. return a > b ? a : b;
  221. }
  222. NORETURN static void __testlib_fail(const std::string& message);
  223. static void __testlib_set_binary(std::FILE* file)
  224. {
  225. #if !defined(unix) && !defined(__APPLE__)
  226. if (NULL != file)
  227. {
  228. #ifdef _MSC_VER
  229. _setmode(_fileno(file), O_BINARY);
  230. #else
  231. #ifdef fileno
  232. setmode(fileno(file), O_BINARY);
  233. #endif
  234. #endif
  235. }
  236. #endif
  237. }
  238. /*
  239. * Very simple regex-like pattern.
  240. * It used for two purposes: validation and generation.
  241. *
  242. * For example, pattern("[a-z]{1,5}").next(rnd) will return
  243. * random string from lowercase latin letters with length
  244. * from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}")
  245. * for the same effect.
  246. *
  247. * Another samples:
  248. * "mike|john" will generate (match) "mike" or "john";
  249. * "-?[1-9][0-9]{0,3}" will generate (match) non-zero integers from -9999 to 9999;
  250. * "id-([ac]|b{2})" will generate (match) "id-a", "id-bb", "id-c";
  251. * "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't
  252. * use it for generations.
  253. *
  254. * You can't use pattern for generation if it contains meta-symbol '*'. Also it
  255. * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].
  256. *
  257. * For matching very simple greedy algorithm is used. For example, pattern
  258. * "[0-9]?1" will not match "1", because of greedy nature of matching.
  259. * Alternations (meta-symbols "|") are processed with brute-force algorithm, so
  260. * do not use many alternations in one expression.
  261. *
  262. * If you want to use one expression many times it is better to compile it into
  263. * a single pattern like "pattern p("[a-z]+")". Later you can use
  264. * "p.matches(std::string s)" or "p.next(random_t& rd)" to check matching or generate
  265. * new string by pattern.
  266. *
  267. * Simpler way to read token and check it for pattern matching is "inf.readToken("[a-z]+")".
  268. */
  269. class random_t;
  270. class pattern
  271. {
  272. public:
  273. /* Create pattern instance by string. */
  274. pattern(std::string s);
  275. /* Generate new string by pattern and given random_t. */
  276. std::string next(random_t& rnd) const;
  277. /* Checks if given string match the pattern. */
  278. bool matches(const std::string& s) const;
  279. /* Returns source string of the pattern. */
  280. std::string src() const;
  281. private:
  282. bool matches(const std::string& s, size_t pos) const;
  283. std::string s;
  284. std::vector<pattern> children;
  285. std::vector<char> chars;
  286. int from;
  287. int to;
  288. };
  289. /*
  290. * Use random_t instances to generate random values. It is preffered
  291. * way to use randoms instead of rand() function or self-written
  292. * randoms.
  293. *
  294. * Testlib defines global variable "rnd" of random_t class.
  295. * Use registerGen(argc, argv) to setup random_t seed be command
  296. * line.
  297. *
  298. * Random generates uniformly distributed values if another strategy is
  299. * not specified explicitly.
  300. */
  301. class random_t
  302. {
  303. private:
  304. long long seed;
  305. static const long long multiplier;
  306. static const long long addend;
  307. static const long long mask;
  308. static const int lim;
  309. long long nextBits(int bits)
  310. {
  311. if (bits <= 48)
  312. {
  313. seed = (seed * multiplier + addend) & mask;
  314. return (long long)(seed >> (48 - bits));
  315. }
  316. else
  317. {
  318. if (bits > 63)
  319. __testlib_fail("random_t::nextBits(int bits): n must be less than 64");
  320. return ((nextBits(31) << 32) ^ nextBits(32));
  321. }
  322. }
  323. public:
  324. /* New random_t with fixed seed. */
  325. random_t()
  326. : seed(3905348978240129619LL)
  327. {
  328. }
  329. /* Sets seed by command line. */
  330. void setSeed(int argc, char* argv[])
  331. {
  332. random_t p;
  333. seed = 3905348978240129619LL;
  334. for (int i = 1; i < argc; i++)
  335. {
  336. std::size_t le = std::strlen(argv[i]);
  337. for (std::size_t j = 0; j < le; j++)
  338. seed = seed * multiplier + (unsigned int)(argv[i][j]) + addend;
  339. seed += multiplier / addend;
  340. }
  341. seed = seed & mask;
  342. }
  343. /* Sets seed by given value. */
  344. void setSeed(long long _seed)
  345. {
  346. _seed = (_seed ^ multiplier) & mask;
  347. seed = _seed;
  348. }
  349. #ifndef __BORLANDC__
  350. /* Random string value by given pattern (see pattern documentation). */
  351. std::string next(const std::string& ptrn)
  352. {
  353. pattern p(ptrn);
  354. return p.next(*this);
  355. }
  356. #else
  357. /* Random string value by given pattern (see pattern documentation). */
  358. std::string next(std::string ptrn)
  359. {
  360. pattern p(ptrn);
  361. return p.next(*this);
  362. }
  363. #endif
  364. /* Random value in range [0, n-1]. */
  365. int next(int n)
  366. {
  367. if (n <= 0)
  368. __testlib_fail("random_t::next(int n): n must be positive");
  369. if ((n & -n) == n) // n is a power of 2
  370. return (int)((n * (long long)nextBits(31)) >> 31);
  371. const long long limit = INT_MAX / n * n;
  372. long long bits;
  373. do {
  374. bits = nextBits(31);
  375. } while (bits >= limit);
  376. return int(bits % n);
  377. }
  378. /* Random value in range [0, n-1]. */
  379. int next(unsigned int n)
  380. {
  381. if (n >= INT_MAX)
  382. __testlib_fail("random_t::next(unsigned int n): n must be less INT_MAX");
  383. return next(int(n));
  384. }
  385. /* Random value in range [0, n-1]. */
  386. long long next(long long n)
  387. {
  388. if (n <= 0)
  389. __testlib_fail("random_t::next(long long n): n must be positive");
  390. const long long limit = __TESTLIB_LONGLONG_MAX / n * n;
  391. long long bits;
  392. do {
  393. bits = nextBits(63);
  394. } while (bits >= limit);
  395. return bits % n;
  396. }
  397. /* Random value in range [0, n-1]. */
  398. unsigned long long next(unsigned long long n)
  399. {
  400. if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))
  401. __testlib_fail("random_t::next(unsigned long long n): n must be less LONGLONG_MAX");
  402. return (unsigned long long)next((long long)(n));
  403. }
  404. /* Returns random value in range [from,to]. */
  405. int next(int from, int to)
  406. {
  407. return int(next((long long)to - from + 1) + from);
  408. }
  409. /* Returns random value in range [from,to]. */
  410. unsigned int next(unsigned int from, unsigned int to)
  411. {
  412. return (unsigned int)(next((long long)to - from + 1) + from);
  413. }
  414. /* Returns random value in range [from,to]. */
  415. long long next(long long from, long long to)
  416. {
  417. return next(to - from + 1) + from;
  418. }
  419. /* Random double value in range [0, 1). */
  420. double next()
  421. {
  422. return (double)(((long long)(nextBits(26)) << 27) + nextBits(27)) / (double)(1LL << 53);
  423. }
  424. /* Random double value in range [0, n). */
  425. double next(double n)
  426. {
  427. return n * next();
  428. }
  429. /* Random double value in range [from, to). */
  430. double next(double from, double to)
  431. {
  432. return next(to - from) + from;
  433. }
  434. /* Returns random element from container. */
  435. template <typename Container>
  436. typename Container::value_type any(const Container& c)
  437. {
  438. size_t size = c.size();
  439. if (size <= 0)
  440. __testlib_fail("random_t::any(const Container& c): c.size() must be positive");
  441. return *(c.begin() + next(size));
  442. }
  443. /* Returns random element from iterator range. */
  444. template <typename Iter>
  445. typename Iter::value_type any(const Iter& begin, const Iter& end)
  446. {
  447. int size = int(end - begin);
  448. if (size <= 0)
  449. __testlib_fail("random_t::any(const Iter& begin, const Iter& end): range must have positive length");
  450. return *(begin + next(size));
  451. }
  452. /* Random string value by given pattern (see pattern documentation). */
  453. #ifdef __GNUC__
  454. __attribute__ ((format (printf, 2, 3)))
  455. #endif
  456. std::string next(const char* format, ...)
  457. {
  458. FMT_TO_RESULT(format, format, ptrn);
  459. return next(ptrn);
  460. }
  461. /*
  462. * Weighted next. If type == 0 than it is usual "next()".
  463. *
  464. * If type = 1, than it returns "max(next(), next())"
  465. * (the number of "max" functions equals to "type").
  466. *
  467. * If type < 0, than "max" function replaces with "min".
  468. */
  469. int wnext(int n, int type)
  470. {
  471. if (n <= 0)
  472. __testlib_fail("random_t::wnext(int n, int type): n must be positive");
  473. if (abs(type) < random_t::lim)
  474. {
  475. int result = next(n);
  476. for (int i = 0; i < +type; i++)
  477. result = __testlib_max(result, next(n));
  478. for (int i = 0; i < -type; i++)
  479. result = __testlib_min(result, next(n));
  480. return result;
  481. }
  482. else
  483. {
  484. double p;
  485. if (type > 0)
  486. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  487. else
  488. p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));
  489. return int(n * p);
  490. }
  491. }
  492. /* See wnext(int, int). It uses the same algorithms. */
  493. long long wnext(long long n, int type)
  494. {
  495. if (n <= 0)
  496. __testlib_fail("random_t::wnext(long long n, int type): n must be positive");
  497. if (abs(type) < random_t::lim)
  498. {
  499. long long result = next(n);
  500. for (int i = 0; i < +type; i++)
  501. result = __testlib_max(result, next(n));
  502. for (int i = 0; i < -type; i++)
  503. result = __testlib_min(result, next(n));
  504. return result;
  505. }
  506. else
  507. {
  508. double p;
  509. if (type > 0)
  510. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  511. else
  512. p = std::pow(next() + 0.0, - type + 1);
  513. return __testlib_min(__testlib_max((long long)(double(n) * p), 0LL), n - 1LL);
  514. }
  515. }
  516. /* See wnext(int, int). It uses the same algorithms. */
  517. double wnext(int type)
  518. {
  519. if (abs(type) < random_t::lim)
  520. {
  521. double result = next();
  522. for (int i = 0; i < +type; i++)
  523. result = __testlib_max(result, next());
  524. for (int i = 0; i < -type; i++)
  525. result = __testlib_min(result, next());
  526. return result;
  527. }
  528. else
  529. {
  530. double p;
  531. if (type > 0)
  532. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  533. else
  534. p = std::pow(next() + 0.0, - type + 1);
  535. return p;
  536. }
  537. }
  538. /* See wnext(int, int). It uses the same algorithms. */
  539. double wnext(double n, int type)
  540. {
  541. if (n <= 0)
  542. __testlib_fail("random_t::wnext(double n, int type): n must be positive");
  543. if (abs(type) < random_t::lim)
  544. {
  545. double result = next();
  546. for (int i = 0; i < +type; i++)
  547. result = __testlib_max(result, next());
  548. for (int i = 0; i < -type; i++)
  549. result = __testlib_min(result, next());
  550. return n * result;
  551. }
  552. else
  553. {
  554. double p;
  555. if (type > 0)
  556. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  557. else
  558. p = std::pow(next() + 0.0, - type + 1);
  559. return n * p;
  560. }
  561. }
  562. /* See wnext(int, int). It uses the same algorithms. */
  563. int wnext(unsigned int n, int type)
  564. {
  565. if (n >= INT_MAX)
  566. __testlib_fail("random_t::wnext(unsigned int n, int type): n must be less INT_MAX");
  567. return wnext(int(n), type);
  568. }
  569. /* Returns weighted random value in range [from, to]. */
  570. int wnext(int from, int to, int type)
  571. {
  572. return wnext(to - from + 1, type) + from;
  573. }
  574. /* Returns weighted random value in range [from, to]. */
  575. int wnext(unsigned int from, unsigned int to, int type)
  576. {
  577. return int(wnext(to - from + 1, type) + from);
  578. }
  579. /* Returns weighted random value in range [from, to]. */
  580. long long wnext(long long from, long long to, int type)
  581. {
  582. return wnext(to - from + 1, type) + from;
  583. }
  584. /* Returns weighted random double value in range [from, to). */
  585. double wnext(double from, double to, int type)
  586. {
  587. return wnext(to - from, type) + from;
  588. }
  589. /* Returns weighted random element from container. */
  590. template <typename Container>
  591. typename Container::value_type wany(const Container& c, int type)
  592. {
  593. size_t size = c.size();
  594. if (size <= 0)
  595. __testlib_fail("random_t::wany(const Container& c, int type): c.size() must be positive");
  596. return *(c.begin() + wnext(size, type));
  597. }
  598. /* Returns weighted random element from iterator range. */
  599. template <typename Iter>
  600. typename Iter::value_type wany(const Iter& begin, const Iter& end, int type)
  601. {
  602. int size = int(end - begin);
  603. if (size <= 0)
  604. __testlib_fail("random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length");
  605. return *(begin + wnext(size, type));
  606. }
  607. };
  608. const int random_t::lim = 25;
  609. const long long random_t::multiplier = 0x5DEECE66DLL;
  610. const long long random_t::addend = 0xBLL;
  611. const long long random_t::mask = (1LL << 48) - 1;
  612. /* Pattern implementation */
  613. bool pattern::matches(const std::string& s) const
  614. {
  615. return matches(s, 0);
  616. }
  617. static bool __pattern_isSlash(const std::string& s, size_t pos)
  618. {
  619. return s[pos] == '\\';
  620. }
  621. #ifdef __GNUC__
  622. __attribute__((pure))
  623. #endif
  624. static bool __pattern_isCommandChar(const std::string& s, size_t pos, char value)
  625. {
  626. if (pos >= s.length())
  627. return false;
  628. int slashes = 0;
  629. int before = int(pos) - 1;
  630. while (before >= 0 && s[before] == '\\')
  631. before--, slashes++;
  632. return slashes % 2 == 0 && s[pos] == value;
  633. }
  634. static char __pattern_getChar(const std::string& s, size_t& pos)
  635. {
  636. if (__pattern_isSlash(s, pos))
  637. pos += 2;
  638. else
  639. pos++;
  640. return s[pos - 1];
  641. }
  642. #ifdef __GNUC__
  643. __attribute__((pure))
  644. #endif
  645. static int __pattern_greedyMatch(const std::string& s, size_t pos, const std::vector<char> chars)
  646. {
  647. int result = 0;
  648. while (pos < s.length())
  649. {
  650. char c = s[pos++];
  651. if (!std::binary_search(chars.begin(), chars.end(), c))
  652. break;
  653. else
  654. result++;
  655. }
  656. return result;
  657. }
  658. std::string pattern::src() const
  659. {
  660. return s;
  661. }
  662. bool pattern::matches(const std::string& s, size_t pos) const
  663. {
  664. std::string result;
  665. if (to > 0)
  666. {
  667. int size = __pattern_greedyMatch(s, pos, chars);
  668. if (size < from)
  669. return false;
  670. if (size > to)
  671. size = to;
  672. pos += size;
  673. }
  674. if (children.size() > 0)
  675. {
  676. for (size_t child = 0; child < children.size(); child++)
  677. if (children[child].matches(s, pos))
  678. return true;
  679. return false;
  680. }
  681. else
  682. return pos == s.length();
  683. }
  684. std::string pattern::next(random_t& rnd) const
  685. {
  686. std::string result;
  687. result.reserve(20);
  688. if (to == INT_MAX)
  689. __testlib_fail("pattern::next(random_t& rnd): can't process character '*' for generation");
  690. if (to > 0)
  691. {
  692. int count = rnd.next(to - from + 1) + from;
  693. for (int i = 0; i < count; i++)
  694. result += chars[rnd.next(int(chars.size()))];
  695. }
  696. if (children.size() > 0)
  697. {
  698. int child = rnd.next(int(children.size()));
  699. result += children[child].next(rnd);
  700. }
  701. return result;
  702. }
  703. static void __pattern_scanCounts(const std::string& s, size_t& pos, int& from, int& to)
  704. {
  705. if (pos >= s.length())
  706. {
  707. from = to = 1;
  708. return;
  709. }
  710. if (__pattern_isCommandChar(s, pos, '{'))
  711. {
  712. std::vector<std::string> parts;
  713. std::string part;
  714. pos++;
  715. while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))
  716. {
  717. if (__pattern_isCommandChar(s, pos, ','))
  718. parts.push_back(part), part = "", pos++;
  719. else
  720. part += __pattern_getChar(s, pos);
  721. }
  722. if (part != "")
  723. parts.push_back(part);
  724. if (!__pattern_isCommandChar(s, pos, '}'))
  725. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  726. pos++;
  727. if (parts.size() < 1 || parts.size() > 2)
  728. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  729. std::vector<int> numbers;
  730. for (size_t i = 0; i < parts.size(); i++)
  731. {
  732. if (parts[i].length() == 0)
  733. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  734. int number;
  735. if (std::sscanf(parts[i].c_str(), "%d", &number) != 1)
  736. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  737. numbers.push_back(number);
  738. }
  739. if (numbers.size() == 1)
  740. from = to = numbers[0];
  741. else
  742. from = numbers[0], to = numbers[1];
  743. if (from > to)
  744. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  745. }
  746. else
  747. {
  748. if (__pattern_isCommandChar(s, pos, '?'))
  749. {
  750. from = 0, to = 1, pos++;
  751. return;
  752. }
  753. if (__pattern_isCommandChar(s, pos, '*'))
  754. {
  755. from = 0, to = INT_MAX, pos++;
  756. return;
  757. }
  758. if (__pattern_isCommandChar(s, pos, '+'))
  759. {
  760. from = 1, to = INT_MAX, pos++;
  761. return;
  762. }
  763. from = to = 1;
  764. }
  765. }
  766. static std::vector<char> __pattern_scanCharSet(const std::string& s, size_t& pos)
  767. {
  768. if (pos >= s.length())
  769. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  770. std::vector<char> result;
  771. if (__pattern_isCommandChar(s, pos, '['))
  772. {
  773. pos++;
  774. bool negative = __pattern_isCommandChar(s, pos, '^');
  775. char prev = 0;
  776. while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))
  777. {
  778. if (__pattern_isCommandChar(s, pos, '-') && prev != 0)
  779. {
  780. pos++;
  781. if (pos + 1 == s.length())
  782. {
  783. result.push_back(prev);
  784. prev = '-';
  785. continue;
  786. }
  787. char next = __pattern_getChar(s, pos);
  788. if (prev > next)
  789. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  790. for (char c = prev; c != next; c++)
  791. result.push_back(c);
  792. result.push_back(next);
  793. prev = 0;
  794. }
  795. else
  796. {
  797. if (prev != 0)
  798. result.push_back(prev);
  799. prev = __pattern_getChar(s, pos);
  800. }
  801. }
  802. if (prev != 0)
  803. result.push_back(prev);
  804. if (!__pattern_isCommandChar(s, pos, ']'))
  805. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  806. pos++;
  807. if (negative)
  808. {
  809. std::sort(result.begin(), result.end());
  810. std::vector<char> actuals;
  811. for (int code = 0; code < 255; code++)
  812. {
  813. char c = char(code);
  814. if (!std::binary_search(result.begin(), result.end(), c))
  815. actuals.push_back(c);
  816. }
  817. result = actuals;
  818. }
  819. std::sort(result.begin(), result.end());
  820. }
  821. else
  822. result.push_back(__pattern_getChar(s, pos));
  823. return result;
  824. }
  825. pattern::pattern(std::string s): s(s), from(0), to(0)
  826. {
  827. std::string t;
  828. for (size_t i = 0; i < s.length(); i++)
  829. if (!__pattern_isCommandChar(s, i, ' '))
  830. t += s[i];
  831. s = t;
  832. int opened = 0;
  833. int firstClose = -1;
  834. std::vector<int> seps;
  835. for (size_t i = 0; i < s.length(); i++)
  836. {
  837. if (__pattern_isCommandChar(s, i, '('))
  838. {
  839. opened++;
  840. continue;
  841. }
  842. if (__pattern_isCommandChar(s, i, ')'))
  843. {
  844. opened--;
  845. if (opened == 0 && firstClose == -1)
  846. firstClose = int(i);
  847. continue;
  848. }
  849. if (opened < 0)
  850. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  851. if (__pattern_isCommandChar(s, i, '|') && opened == 0)
  852. seps.push_back(int(i));
  853. }
  854. if (opened != 0)
  855. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  856. if (seps.size() == 0 && firstClose + 1 == (int)s.length()
  857. && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))
  858. {
  859. children.push_back(pattern(s.substr(1, s.length() - 2)));
  860. }
  861. else
  862. {
  863. if (seps.size() > 0)
  864. {
  865. seps.push_back(s.length());
  866. int last = 0;
  867. for (size_t i = 0; i < seps.size(); i++)
  868. {
  869. children.push_back(pattern(s.substr(last, seps[i] - last)));
  870. last = seps[i] + 1;
  871. }
  872. }
  873. else
  874. {
  875. size_t pos = 0;
  876. chars = __pattern_scanCharSet(s, pos);
  877. __pattern_scanCounts(s, pos, from, to);
  878. if (pos < s.length())
  879. children.push_back(pattern(s.substr(pos)));
  880. }
  881. }
  882. }
  883. /* End of pattern implementation */
  884. template <typename C>
  885. inline bool isEof(C c)
  886. {
  887. return (c == EOF || c == EOFC);
  888. }
  889. template <typename C>
  890. inline bool isEoln(C c)
  891. {
  892. return (c == LF || c == CR);
  893. }
  894. template<typename C>
  895. inline bool isBlanks(C c)
  896. {
  897. return (c == LF || c == CR || c == SPACE || c == TAB);
  898. }
  899. enum TMode
  900. {
  901. _input, _output, _answer
  902. };
  903. /* Outcomes 6-15 are reserved for future use. */
  904. enum TResult
  905. {
  906. _ok = 0,
  907. _wa = 1,
  908. _pe = 2,
  909. _fail = 3,
  910. _dirt = 4,
  911. _points = 5,
  912. _partially = 16
  913. };
  914. enum TTestlibMode
  915. {
  916. _unknown, _checker, _validator, _generator, _interactor
  917. };
  918. #define _pc(exitCode) (TResult(_partially + (exitCode)))
  919. /* Outcomes 6-15 are reserved for future use. */
  920. const std::string outcomes[] = {
  921. "accepted",
  922. "wrong-answer",
  923. "presentation-error",
  924. "fail",
  925. "fail",
  926. #ifndef PCMS2
  927. "points",
  928. #else
  929. "relative-scoring",
  930. #endif
  931. "reserved",
  932. "reserved",
  933. "reserved",
  934. "reserved",
  935. "reserved",
  936. "reserved",
  937. "reserved",
  938. "reserved",
  939. "reserved",
  940. "reserved",
  941. "partially-correct"
  942. };
  943. class InputStreamReader
  944. {
  945. public:
  946. virtual int curChar() = 0;
  947. virtual int nextChar() = 0;
  948. virtual void skipChar() = 0;
  949. virtual void unreadChar(int c) = 0;
  950. virtual std::string getName() = 0;
  951. virtual bool eof() = 0;
  952. virtual ~InputStreamReader() = 0;
  953. };
  954. InputStreamReader::~InputStreamReader()
  955. {
  956. // No operations.
  957. }
  958. class FileInputStreamReader: public InputStreamReader
  959. {
  960. private:
  961. std::FILE* file;
  962. std::string name;
  963. public:
  964. FileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name)
  965. {
  966. // No operations.
  967. }
  968. int curChar()
  969. {
  970. if (feof(file))
  971. return EOF;
  972. else
  973. {
  974. int c = getc(file);
  975. ungetc(c, file);
  976. return c;
  977. }
  978. }
  979. int nextChar()
  980. {
  981. if (feof(file))
  982. return EOF;
  983. else
  984. return getc(file);
  985. }
  986. void skipChar()
  987. {
  988. getc(file);
  989. }
  990. void unreadChar(int c)
  991. {
  992. ungetc(c, file);
  993. }
  994. std::string getName()
  995. {
  996. return name;
  997. }
  998. bool eof()
  999. {
  1000. if (feof(file))
  1001. return true;
  1002. else
  1003. {
  1004. int c = getc(file);
  1005. bool result = (c == EOF);
  1006. ungetc(c, file);
  1007. return result;
  1008. }
  1009. }
  1010. };
  1011. class BufferedFileInputStreamReader: public InputStreamReader
  1012. {
  1013. private:
  1014. static const size_t BUFFER_SIZE;
  1015. static const size_t MAX_UNREAD_COUNT;
  1016. std::FILE* file;
  1017. char* buffer;
  1018. bool* isEof;
  1019. int bufferPos;
  1020. size_t bufferSize;
  1021. std::string name;
  1022. bool refill()
  1023. {
  1024. if (NULL == file)
  1025. __testlib_fail("BufferedFileInputStreamReader: file == NULL (" + getName() + ")");
  1026. if (bufferPos >= int(bufferSize))
  1027. {
  1028. size_t readSize = fread(
  1029. buffer + MAX_UNREAD_COUNT,
  1030. 1,
  1031. BUFFER_SIZE - MAX_UNREAD_COUNT,
  1032. file
  1033. );
  1034. if (readSize < BUFFER_SIZE - MAX_UNREAD_COUNT
  1035. && ferror(file))
  1036. __testlib_fail("BufferedFileInputStreamReader: unable to read (" + getName() + ")");
  1037. bufferSize = MAX_UNREAD_COUNT + readSize;
  1038. bufferPos = int(MAX_UNREAD_COUNT);
  1039. std::memset(isEof + MAX_UNREAD_COUNT, 0, sizeof(isEof[0]) * readSize);
  1040. return readSize > 0;
  1041. }
  1042. else
  1043. return true;
  1044. }
  1045. public:
  1046. BufferedFileInputStreamReader(std::FILE* file, const std::string& name): file(file), name(name)
  1047. {
  1048. buffer = new char[BUFFER_SIZE];
  1049. isEof = new bool[BUFFER_SIZE];
  1050. bufferSize = MAX_UNREAD_COUNT;
  1051. bufferPos = int(MAX_UNREAD_COUNT);
  1052. }
  1053. ~BufferedFileInputStreamReader()
  1054. {
  1055. if (NULL != buffer)
  1056. {
  1057. delete[] buffer;
  1058. buffer = NULL;
  1059. }
  1060. if (NULL != isEof)
  1061. {
  1062. delete[] isEof;
  1063. isEof = NULL;
  1064. }
  1065. }
  1066. int curChar()
  1067. {
  1068. if (!refill())
  1069. return EOF;
  1070. return isEof[bufferPos] ? EOF : buffer[bufferPos];
  1071. }
  1072. int nextChar()
  1073. {
  1074. if (!refill())
  1075. return EOF;
  1076. return isEof[bufferPos] ? EOF : buffer[bufferPos++];
  1077. }
  1078. void skipChar()
  1079. {
  1080. bufferPos++;
  1081. }
  1082. void unreadChar(int c)
  1083. {
  1084. bufferPos--;
  1085. if (bufferPos < 0)
  1086. __testlib_fail("BufferedFileInputStreamReader::unreadChar(int): bufferPos < 0");
  1087. isEof[bufferPos] = (c == EOF);
  1088. buffer[bufferPos] = char(c == EOF ? EOFC : c);
  1089. }
  1090. std::string getName()
  1091. {
  1092. return name;
  1093. }
  1094. bool eof()
  1095. {
  1096. return !refill() || EOF == curChar();
  1097. }
  1098. };
  1099. const size_t BufferedFileInputStreamReader::BUFFER_SIZE = 1000000;
  1100. const size_t BufferedFileInputStreamReader::MAX_UNREAD_COUNT = 100;
  1101. /*
  1102. * Streams to be used for reading data in checkers or validators.
  1103. * Each read*() method moves pointer to the next character after the
  1104. * read value.
  1105. */
  1106. struct InStream
  1107. {
  1108. /* Do not use them. */
  1109. InStream();
  1110. ~InStream();
  1111. InputStreamReader* reader;
  1112. std::FILE* file;
  1113. std::string name;
  1114. TMode mode;
  1115. bool opened;
  1116. bool stdfile;
  1117. bool strict;
  1118. int wordReserveSize;
  1119. std::string _tmpReadToken;
  1120. void init(std::string fileName, TMode mode);
  1121. void init(std::FILE* f, TMode mode);
  1122. /* Moves stream pointer to the first non-white-space character or EOF. */
  1123. void skipBlanks();
  1124. /* Returns current character in the stream. Doesn't remove it from stream. */
  1125. char curChar();
  1126. /* Moves stream pointer one character forward. */
  1127. void skipChar();
  1128. /* Returns current character and moves pointer one character forward. */
  1129. char nextChar();
  1130. /* Returns current character and moves pointer one character forward. */
  1131. char readChar();
  1132. /* As "readChar()" but ensures that the result is equal to given parameter. */
  1133. char readChar(char c);
  1134. /* As "readChar()" but ensures that the result is equal to the space (code=32). */
  1135. char readSpace();
  1136. /* Puts back the character into the stream. */
  1137. void unreadChar(char c);
  1138. /* Reopens stream, you should not use it. */
  1139. void reset();
  1140. /* Checks that current position is EOF. If not it doesn't move stream pointer. */
  1141. bool eof();
  1142. /* Moves pointer to the first non-white-space character and calls "eof()". */
  1143. bool seekEof();
  1144. /*
  1145. * Checks that current position contains EOLN.
  1146. * If not it doesn't move stream pointer.
  1147. * In strict mode expects "#13#10" for windows or "#10" for other platforms.
  1148. */
  1149. bool eoln();
  1150. /* Moves pointer to the first non-space and non-tab character and calls "eoln()". */
  1151. bool seekEoln();
  1152. /* Moves stream pointer to the first character of the next line (if exists). */
  1153. void nextLine();
  1154. /*
  1155. * Reads new token. Ignores white-spaces into the non-strict mode
  1156. * (strict mode is used in validators usually).
  1157. */
  1158. std::string readWord();
  1159. /* The same as "readWord()", it is preffered to use "readToken()". */
  1160. std::string readToken();
  1161. /* The same as "readWord()", but ensures that token matches to given pattern. */
  1162. std::string readWord(const std::string& ptrn, const std::string& variableName = "");
  1163. std::string readWord(const pattern& p, const std::string& variableName = "");
  1164. /* The same as "readToken()", but ensures that token matches to given pattern. */
  1165. std::string readToken(const std::string& ptrn, const std::string& variableName = "");
  1166. std::string readToken(const pattern& p, const std::string& variableName = "");
  1167. void readWordTo(std::string& result);
  1168. void readWordTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1169. void readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1170. void readTokenTo(std::string& result);
  1171. void readTokenTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1172. void readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1173. /*
  1174. * Reads new long long value. Ignores white-spaces into the non-strict mode
  1175. * (strict mode is used in validators usually).
  1176. */
  1177. long long readLong();
  1178. /*
  1179. * Reads new int. Ignores white-spaces into the non-strict mode
  1180. * (strict mode is used in validators usually).
  1181. */
  1182. int readInteger();
  1183. /*
  1184. * Reads new int. Ignores white-spaces into the non-strict mode
  1185. * (strict mode is used in validators usually).
  1186. */
  1187. int readInt();
  1188. /* As "readLong()" but ensures that value in the range [minv,maxv]. */
  1189. long long readLong(long long minv, long long maxv, const std::string& variableName = "");
  1190. /* As "readInteger()" but ensures that value in the range [minv,maxv]. */
  1191. int readInteger(int minv, int maxv, const std::string& variableName = "");
  1192. /* As "readInt()" but ensures that value in the range [minv,maxv]. */
  1193. int readInt(int minv, int maxv, const std::string& variableName = "");
  1194. /*
  1195. * Reads new double. Ignores white-spaces into the non-strict mode
  1196. * (strict mode is used in validators usually).
  1197. */
  1198. double readReal();
  1199. /*
  1200. * Reads new double. Ignores white-spaces into the non-strict mode
  1201. * (strict mode is used in validators usually).
  1202. */
  1203. double readDouble();
  1204. /* As "readReal()" but ensures that value in the range [minv,maxv]. */
  1205. double readReal(double minv, double maxv, const std::string& variableName = "");
  1206. /* As "readDouble()" but ensures that value in the range [minv,maxv]. */
  1207. double readDouble(double minv, double maxv, const std::string& variableName = "");
  1208. /*
  1209. * As "readReal()" but ensures that value in the range [minv,maxv] and
  1210. * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]
  1211. * and number is in the form "[-]digit(s)[.digit(s)]".
  1212. */
  1213. double readStrictReal(double minv, double maxv,
  1214. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1215. const std::string& variableName = "");
  1216. /*
  1217. * As "readDouble()" but ensures that value in the range [minv,maxv] and
  1218. * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]
  1219. * and number is in the form "[-]digit(s)[.digit(s)]".
  1220. */
  1221. double readStrictDouble(double minv, double maxv,
  1222. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1223. const std::string& variableName = "");
  1224. /* As readLine(). */
  1225. std::string readString();
  1226. /* See readLine(). */
  1227. void readStringTo(std::string& result);
  1228. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1229. std::string readString(const pattern& p, const std::string& variableName = "");
  1230. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1231. std::string readString(const std::string& ptrn, const std::string& variableName = "");
  1232. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1233. void readStringTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1234. /* The same as "readLine()/readString()", but ensures that line matches to the given pattern. */
  1235. void readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1236. /*
  1237. * Reads line from the current position to EOLN or EOF. Moves stream pointer to
  1238. * the first character of the new line (if possible).
  1239. */
  1240. std::string readLine();
  1241. /* See readLine(). */
  1242. void readLineTo(std::string& result);
  1243. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1244. std::string readLine(const pattern& p, const std::string& variableName = "");
  1245. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1246. std::string readLine(const std::string& ptrn, const std::string& variableName = "");
  1247. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1248. void readLineTo(std::string& result, const pattern& p, const std::string& variableName = "");
  1249. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  1250. void readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName = "");
  1251. /* Reads EOLN or fails. Use it in validators. Calls "eoln()" method internally. */
  1252. void readEoln();
  1253. /* Reads EOF or fails. Use it in validators. Calls "eof()" method internally. */
  1254. void readEof();
  1255. /*
  1256. * Quit-functions aborts program with <result> and <message>:
  1257. * input/answer streams replaces any result to FAIL.
  1258. */
  1259. NORETURN void quit(TResult result, const char* msg);
  1260. /*
  1261. * Quit-functions aborts program with <result> and <message>:
  1262. * input/answer streams replaces any result to FAIL.
  1263. */
  1264. NORETURN void quitf(TResult result, const char* msg, ...);
  1265. /*
  1266. * Quit-functions aborts program with <result> and <message>:
  1267. * input/answer streams replaces any result to FAIL.
  1268. */
  1269. NORETURN void quits(TResult result, std::string msg);
  1270. void close();
  1271. const static WORD LightGray = 0x07;
  1272. const static WORD LightRed = 0x0c;
  1273. const static WORD LightCyan = 0x0b;
  1274. const static WORD LightGreen = 0x0a;
  1275. const static WORD LightYellow = 0x0e;
  1276. static void textColor(WORD color);
  1277. static void quitscr(WORD color, const char* msg);
  1278. static void quitscrS(WORD color, std::string msg);
  1279. void xmlSafeWrite(std::FILE * file, const char* msg);
  1280. private:
  1281. InStream(const InStream&);
  1282. InStream& operator =(const InStream&);
  1283. };
  1284. InStream inf;
  1285. InStream ouf;
  1286. InStream ans;
  1287. bool appesMode;
  1288. std::string resultName;
  1289. std::string checkerName = "untitled checker";
  1290. random_t rnd;
  1291. TTestlibMode testlibMode = _unknown;
  1292. double __testlib_points = std::numeric_limits<float>::infinity();
  1293. struct TestlibFinalizeGuard
  1294. {
  1295. static bool alive;
  1296. int quitCount, readEofCount;
  1297. TestlibFinalizeGuard() : quitCount(0), readEofCount(0)
  1298. {
  1299. // No operations.
  1300. }
  1301. ~TestlibFinalizeGuard()
  1302. {
  1303. bool _alive = alive;
  1304. alive = false;
  1305. if (_alive)
  1306. {
  1307. if (testlibMode == _checker && quitCount == 0)
  1308. __testlib_fail("Checker must end with quit or quitf call.");
  1309. if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)
  1310. __testlib_fail("Validator must end with readEof call.");
  1311. }
  1312. }
  1313. };
  1314. bool TestlibFinalizeGuard::alive = true;
  1315. TestlibFinalizeGuard testlibFinalizeGuard;
  1316. /* Interactor streams.
  1317. */
  1318. std::fstream tout;
  1319. /* implementation
  1320. */
  1321. template <typename T>
  1322. static std::string vtos(const T& t)
  1323. {
  1324. std::string s;
  1325. std::stringstream ss;
  1326. ss << t;
  1327. ss >> s;
  1328. return s;
  1329. }
  1330. InStream::InStream()
  1331. {
  1332. file = NULL;
  1333. name = "";
  1334. mode = _input;
  1335. strict = false;
  1336. stdfile = false;
  1337. wordReserveSize = 4;
  1338. }
  1339. InStream::~InStream()
  1340. {
  1341. if (NULL != reader)
  1342. {
  1343. delete reader;
  1344. reader = NULL;
  1345. }
  1346. }
  1347. #ifdef __GNUC__
  1348. __attribute__((const))
  1349. #endif
  1350. int resultExitCode(TResult r)
  1351. {
  1352. if (r == _ok)
  1353. return OK_EXIT_CODE;
  1354. if (r == _wa)
  1355. return WA_EXIT_CODE;
  1356. if (r == _pe)
  1357. return PE_EXIT_CODE;
  1358. if (r == _fail)
  1359. return FAIL_EXIT_CODE;
  1360. if (r == _dirt)
  1361. return DIRT_EXIT_CODE;
  1362. if (r == _points)
  1363. return POINTS_EXIT_CODE;
  1364. if (r >= _partially)
  1365. return PC_BASE_EXIT_CODE + (r - _partially);
  1366. return FAIL_EXIT_CODE;
  1367. }
  1368. void InStream::textColor(WORD color)
  1369. {
  1370. #if defined(ON_WINDOWS) && (!defined(_MSC_VER) || _MSC_VER>1400)
  1371. HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
  1372. SetConsoleTextAttribute(handle, color);
  1373. #endif
  1374. }
  1375. #ifdef __GNUC__
  1376. __attribute__ ((noreturn))
  1377. #endif
  1378. NORETURN void halt(int exitCode)
  1379. {
  1380. #ifdef FOOTER
  1381. InStream::textColor(InStream::LightGray);
  1382. std::fprintf(stderr, "Checker: \"%s\"\n", checkerName.c_str());
  1383. std::fprintf(stderr, "Exit code: %d\n", exitCode);
  1384. InStream::textColor(InStream::LightGray);
  1385. #endif
  1386. std::exit(exitCode);
  1387. }
  1388. #ifdef __GNUC__
  1389. __attribute__ ((noreturn))
  1390. #endif
  1391. NORETURN void InStream::quit(TResult result, const char* msg)
  1392. {
  1393. if (TestlibFinalizeGuard::alive)
  1394. testlibFinalizeGuard.quitCount++;
  1395. if (mode != _output && result != _fail)
  1396. quits(_fail, std::string(msg) + " (" + name + ")");
  1397. std::FILE * resultFile;
  1398. std::string errorName;
  1399. if (result == _ok)
  1400. {
  1401. if (testlibMode != _interactor && !ouf.seekEof())
  1402. quit(_dirt, "Extra information in the output file");
  1403. }
  1404. int pctype = result - _partially;
  1405. bool isPartial = false;
  1406. switch (result)
  1407. {
  1408. case _ok:
  1409. errorName = "ok ";
  1410. quitscrS(LightGreen, errorName);
  1411. break;
  1412. case _wa:
  1413. errorName = "wrong answer ";
  1414. quitscrS(LightRed, errorName);
  1415. break;
  1416. case _pe:
  1417. errorName = "wrong output format ";
  1418. quitscrS(LightRed, errorName);
  1419. break;
  1420. case _fail:
  1421. errorName = "FAIL ";
  1422. quitscrS(LightRed, errorName);
  1423. break;
  1424. case _dirt:
  1425. errorName = "wrong output format ";
  1426. quitscrS(LightCyan, errorName);
  1427. result = _pe;
  1428. break;
  1429. case _points:
  1430. errorName = "points ";
  1431. quitscrS(LightYellow, errorName);
  1432. break;
  1433. default:
  1434. if (result >= _partially)
  1435. {
  1436. char message[1023];
  1437. std::sprintf(message, "partially correct (%d) ", pctype);
  1438. errorName = std::string(message);
  1439. isPartial = true;
  1440. quitscrS(LightYellow, errorName);
  1441. }
  1442. else
  1443. quit(_fail, "What is the code ??? ");
  1444. }
  1445. if (resultName != "")
  1446. {
  1447. resultFile = std::fopen(resultName.c_str(), "w");
  1448. if (resultFile == NULL)
  1449. quit(_fail, "Can not write to Result file");
  1450. if (appesMode)
  1451. {
  1452. fprintf(resultFile, "<?xml version=\"1.0\" encoding=\"windows-1251\"?>");
  1453. if (isPartial)
  1454. fprintf(resultFile, "<result outcome = \"%s\" pctype = \"%d\">", outcomes[(int)_partially].c_str(), pctype);
  1455. else
  1456. {
  1457. if (result != _points)
  1458. fprintf(resultFile, "<result outcome = \"%s\">", outcomes[(int)result].c_str());
  1459. else
  1460. {
  1461. if (__testlib_points == std::numeric_limits<float>::infinity())
  1462. quit(_fail, "Expected points, but infinity found");
  1463. fprintf(resultFile, "<result outcome = \"%s\" points = \"%.10f\">", outcomes[(int)result].c_str(), __testlib_points);
  1464. }
  1465. }
  1466. xmlSafeWrite(resultFile, msg);
  1467. fprintf(resultFile, "</result>\n");
  1468. }
  1469. else
  1470. fprintf(resultFile, "%s", msg);
  1471. if (NULL == resultFile || fclose(resultFile) != 0)
  1472. quit(_fail, "Can not write to Result file");
  1473. }
  1474. quitscr(LightGray, msg);
  1475. std::fprintf(stderr, "\n");
  1476. if (inf.file)
  1477. fclose(inf.file);
  1478. if (ouf.file)
  1479. fclose(ouf.file);
  1480. if (ans.file)
  1481. fclose(ans.file);
  1482. if (tout.is_open())
  1483. tout.close();
  1484. textColor(LightGray);
  1485. if (resultName != "")
  1486. std::fprintf(stderr, "See file to check exit message\n");
  1487. halt(resultExitCode(result));
  1488. }
  1489. #ifdef __GNUC__
  1490. __attribute__ ((format (printf, 3, 4)))
  1491. __attribute__ ((noreturn))
  1492. #endif
  1493. NORETURN void InStream::quitf(TResult result, const char* msg, ...)
  1494. {
  1495. FMT_TO_RESULT(msg, msg, message);
  1496. InStream::quit(result, message.c_str());
  1497. }
  1498. #ifdef __GNUC__
  1499. __attribute__ ((noreturn))
  1500. #endif
  1501. NORETURN void InStream::quits(TResult result, std::string msg)
  1502. {
  1503. InStream::quit(result, msg.c_str());
  1504. }
  1505. void InStream::xmlSafeWrite(std::FILE * file, const char* msg)
  1506. {
  1507. size_t lmsg = strlen(msg);
  1508. for (size_t i = 0; i < lmsg; i++)
  1509. {
  1510. if (msg[i] == '&')
  1511. {
  1512. fprintf(file, "%s", "&amp;");
  1513. continue;
  1514. }
  1515. if (msg[i] == '<')
  1516. {
  1517. fprintf(file, "%s", "&lt;");
  1518. continue;
  1519. }
  1520. if (msg[i] == '>')
  1521. {
  1522. fprintf(file, "%s", "&gt;");
  1523. continue;
  1524. }
  1525. if (msg[i] == '"')
  1526. {
  1527. fprintf(file, "%s", "&quot;");
  1528. continue;
  1529. }
  1530. if (0 <= msg[i] && msg[i] <= 31)
  1531. {
  1532. fprintf(file, "%c", '.');
  1533. continue;
  1534. }
  1535. fprintf(file, "%c", msg[i]);
  1536. }
  1537. }
  1538. void InStream::quitscrS(WORD color, std::string msg)
  1539. {
  1540. quitscr(color, msg.c_str());
  1541. }
  1542. void InStream::quitscr(WORD color, const char* msg)
  1543. {
  1544. if (resultName == "")
  1545. {
  1546. textColor(color);
  1547. std::fprintf(stderr, "%s", msg);
  1548. textColor(LightGray);
  1549. }
  1550. }
  1551. void InStream::reset()
  1552. {
  1553. if (opened && stdfile)
  1554. quit(_fail, "Can't reset standard handle");
  1555. if (opened)
  1556. close();
  1557. if (!stdfile)
  1558. if (NULL == (file = std::fopen(name.c_str(), "rb")))
  1559. {
  1560. if (mode == _output)
  1561. quits(_pe, std::string("File not found: \"") + name + "\"");
  1562. }
  1563. opened = true;
  1564. __testlib_set_binary(file);
  1565. if (stdfile)
  1566. reader = new FileInputStreamReader(file, name);
  1567. else
  1568. reader = new BufferedFileInputStreamReader(file, name);
  1569. }
  1570. void InStream::init(std::string fileName, TMode mode)
  1571. {
  1572. opened = false;
  1573. name = fileName;
  1574. stdfile = false;
  1575. this->mode = mode;
  1576. reset();
  1577. }
  1578. void InStream::init(std::FILE* f, TMode mode)
  1579. {
  1580. opened = false;
  1581. name = "untitled";
  1582. if (f == stdin)
  1583. name = "stdin", stdfile = true;
  1584. if (f == stdout)
  1585. name = "stdout", stdfile = true;
  1586. if (f == stderr)
  1587. name = "stderr", stdfile = true;
  1588. this->file = f;
  1589. this->mode = mode;
  1590. reset();
  1591. }
  1592. char InStream::curChar()
  1593. {
  1594. int c = reader->curChar();
  1595. return char(c != EOF ? c : EOFC);
  1596. }
  1597. char InStream::nextChar()
  1598. {
  1599. int c = reader->nextChar();
  1600. return char(c != EOF ? c : EOFC);
  1601. }
  1602. char InStream::readChar()
  1603. {
  1604. return nextChar();
  1605. }
  1606. char InStream::readChar(char c)
  1607. {
  1608. char found = readChar();
  1609. if (c != found)
  1610. {
  1611. if (!isEoln(found))
  1612. quit(_pe, ("Unexpected character '" + std::string(1, found) + "', but '" + std::string(1, c) + "' expected").c_str());
  1613. else
  1614. quit(_pe, ("Unexpected character " + ("#" + vtos(int(found))) + ", but '" + std::string(1, c) + "' expected").c_str());
  1615. }
  1616. return found;
  1617. }
  1618. char InStream::readSpace()
  1619. {
  1620. return readChar(' ');
  1621. }
  1622. void InStream::unreadChar(char c)
  1623. {
  1624. reader->unreadChar(c);
  1625. }
  1626. void InStream::skipChar()
  1627. {
  1628. reader->skipChar();
  1629. }
  1630. void InStream::skipBlanks()
  1631. {
  1632. while (isBlanks(reader->curChar()))
  1633. reader->skipChar();
  1634. }
  1635. std::string InStream::readWord()
  1636. {
  1637. readWordTo(_tmpReadToken);
  1638. return _tmpReadToken;
  1639. }
  1640. void InStream::readWordTo(std::string& result)
  1641. {
  1642. if (!strict)
  1643. skipBlanks();
  1644. int cur = reader->nextChar();
  1645. if (cur == EOF)
  1646. quit(_pe, "Unexpected end of file - token expected");
  1647. if (isBlanks(cur))
  1648. quit(_pe, "Unexpected white-space - token expected");
  1649. result.clear();
  1650. while (!(isBlanks(cur) || cur == EOF))
  1651. {
  1652. result += char(cur);
  1653. cur = reader->nextChar();
  1654. }
  1655. reader->unreadChar(cur);
  1656. if (result.length() == 0)
  1657. quit(_pe, "Unexpected end of file or white-space - token expected");
  1658. }
  1659. std::string InStream::readToken()
  1660. {
  1661. return readWord();
  1662. }
  1663. void InStream::readTokenTo(std::string& result)
  1664. {
  1665. readWordTo(result);
  1666. }
  1667. static std::string __testlib_part(const std::string& s)
  1668. {
  1669. if (s.length() <= 64)
  1670. return s;
  1671. else
  1672. return s.substr(0, 30) + "..." + s.substr(s.length() - 31, 31);
  1673. }
  1674. std::string InStream::readWord(const pattern& p, const std::string& variableName)
  1675. {
  1676. readWordTo(_tmpReadToken);
  1677. if (!p.matches(_tmpReadToken))
  1678. {
  1679. if (variableName.empty())
  1680. quit(_wa, ("Token \"" + __testlib_part(_tmpReadToken) + "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  1681. else
  1682. quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(_tmpReadToken) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  1683. }
  1684. return _tmpReadToken;
  1685. }
  1686. std::string InStream::readWord(const std::string& ptrn, const std::string& variableName)
  1687. {
  1688. return readWord(pattern(ptrn), variableName);
  1689. }
  1690. std::string InStream::readToken(const pattern& p, const std::string& variableName)
  1691. {
  1692. return readWord(p, variableName);
  1693. }
  1694. std::string InStream::readToken(const std::string& ptrn, const std::string& variableName)
  1695. {
  1696. return readWord(ptrn, variableName);
  1697. }
  1698. void InStream::readWordTo(std::string& result, const pattern& p, const std::string& variableName)
  1699. {
  1700. readWordTo(result);
  1701. if (!p.matches(result))
  1702. {
  1703. if (variableName.empty())
  1704. quit(_wa, ("Token \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  1705. else
  1706. quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(result) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  1707. }
  1708. }
  1709. void InStream::readWordTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  1710. {
  1711. return readWordTo(result, pattern(ptrn), variableName);
  1712. }
  1713. void InStream::readTokenTo(std::string& result, const pattern& p, const std::string& variableName)
  1714. {
  1715. return readWordTo(result, p, variableName);
  1716. }
  1717. void InStream::readTokenTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  1718. {
  1719. return readWordTo(result, ptrn, variableName);
  1720. }
  1721. #ifdef __GNUC__
  1722. __attribute__((pure))
  1723. #endif
  1724. static inline bool equals(long long integer, const char* s)
  1725. {
  1726. if (integer == LLONG_MIN)
  1727. return strcmp(s, "-9223372036854775808") == 0;
  1728. if (integer == 0LL)
  1729. return strcmp(s, "0") == 0;
  1730. size_t length = strlen(s);
  1731. if (length == 0)
  1732. return false;
  1733. if (integer < 0 && s[0] != '-')
  1734. return false;
  1735. if (integer < 0)
  1736. s++, length--, integer = -integer;
  1737. if (length == 0)
  1738. return false;
  1739. while (integer > 0)
  1740. {
  1741. int digit = int(integer % 10);
  1742. if (s[length - 1] != '0' + digit)
  1743. return false;
  1744. length--;
  1745. integer /= 10;
  1746. }
  1747. return length == 0;
  1748. }
  1749. static inline double stringToDouble(InStream& in, const char* buffer)
  1750. {
  1751. double retval;
  1752. size_t length = strlen(buffer);
  1753. for (size_t i = 0; i < length; i++)
  1754. if (isBlanks(buffer[i]))
  1755. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1756. char* suffix = new char[length + 1];
  1757. int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix);
  1758. bool empty = strlen(suffix) == 0;
  1759. delete[] suffix;
  1760. if (scanned == 1 || (scanned == 2 && empty))
  1761. return retval;
  1762. else
  1763. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1764. }
  1765. static inline double stringToStrictDouble(InStream& in, const char* buffer, int minAfterPointDigitCount, int maxAfterPointDigitCount)
  1766. {
  1767. if (minAfterPointDigitCount < 0)
  1768. in.quit(_fail, "stringToStrictDouble: minAfterPointDigitCount should be non-negative.");
  1769. if (minAfterPointDigitCount > maxAfterPointDigitCount)
  1770. in.quit(_fail, "stringToStrictDouble: minAfterPointDigitCount should be less or equal to maxAfterPointDigitCount.");
  1771. double retval;
  1772. size_t length = strlen(buffer);
  1773. if (length == 0 || length > 1000)
  1774. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1775. if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))
  1776. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1777. int pointPos = -1;
  1778. for (size_t i = 1; i + 1 < length; i++)
  1779. {
  1780. if (buffer[i] == '.')
  1781. {
  1782. if (pointPos > -1)
  1783. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1784. pointPos = int(i);
  1785. }
  1786. if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))
  1787. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1788. }
  1789. if (buffer[length - 1] < '0' || buffer[length - 1] > '9')
  1790. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1791. int afterDigitsCount = (pointPos == -1 ? 0 : int(length) - pointPos - 1);
  1792. if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)
  1793. in.quit(_pe, ("Expected strict double with number of digits after point in range ["
  1794. + vtos(minAfterPointDigitCount)
  1795. + ","
  1796. + vtos(maxAfterPointDigitCount)
  1797. + "], but \"" + __testlib_part(buffer) + "\" found").c_str()
  1798. );
  1799. int firstDigitPos = -1;
  1800. for (size_t i = 0; i < length; i++)
  1801. if (buffer[i] >= '0' && buffer[i] <= '9')
  1802. {
  1803. firstDigitPos = int(i);
  1804. break;
  1805. }
  1806. if (firstDigitPos > 1 || firstDigitPos == -1)
  1807. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1808. if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length)
  1809. && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')
  1810. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1811. char* suffix = new char[length + 1];
  1812. int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix);
  1813. bool empty = strlen(suffix) == 0;
  1814. delete[] suffix;
  1815. if (scanned == 1 || (scanned == 2 && empty))
  1816. return retval;
  1817. else
  1818. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1819. }
  1820. static inline long long stringToLongLong(InStream& in, const char* buffer)
  1821. {
  1822. if (strcmp(buffer, "-9223372036854775808") == 0)
  1823. return LLONG_MIN;
  1824. bool minus = false;
  1825. size_t length = strlen(buffer);
  1826. if (length > 1 && buffer[0] == '-')
  1827. minus = true;
  1828. if (length > 20)
  1829. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1830. long long retval = 0LL;
  1831. int zeroes = 0;
  1832. int processingZeroes = true;
  1833. for (int i = (minus ? 1 : 0); i < int(length); i++)
  1834. {
  1835. if (buffer[i] == '0' && processingZeroes)
  1836. zeroes++;
  1837. else
  1838. processingZeroes = false;
  1839. if (buffer[i] < '0' || buffer[i] > '9')
  1840. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1841. retval = retval * 10 + (buffer[i] - '0');
  1842. }
  1843. if (retval < 0)
  1844. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1845. if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)
  1846. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1847. retval = (minus ? -retval : +retval);
  1848. if (length < 19)
  1849. return retval;
  1850. if (equals(retval, buffer))
  1851. return retval;
  1852. else
  1853. in.quit(_pe, ("Expected int64, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1854. }
  1855. int InStream::readInteger()
  1856. {
  1857. if (!strict && seekEof())
  1858. quit(_pe, "Unexpected end of file - int32 expected");
  1859. readWordTo(_tmpReadToken);
  1860. long long value = stringToLongLong(*this, _tmpReadToken.c_str());
  1861. if (value < INT_MIN || value > INT_MAX)
  1862. quit(_pe, ("Expected int32, but \"" + _tmpReadToken + "\" found").c_str());
  1863. return int(value);
  1864. }
  1865. long long InStream::readLong()
  1866. {
  1867. if (!strict && seekEof())
  1868. quit(_pe, "Unexpected end of file - int64 expected");
  1869. readWordTo(_tmpReadToken);
  1870. return stringToLongLong(*this, _tmpReadToken.c_str());
  1871. }
  1872. long long InStream::readLong(long long minv, long long maxv, const std::string& variableName)
  1873. {
  1874. long long result = readLong();
  1875. if (result < minv || result > maxv)
  1876. {
  1877. if (variableName.empty())
  1878. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1879. else
  1880. quit(_wa, ("Integer parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1881. }
  1882. return result;
  1883. }
  1884. int InStream::readInt()
  1885. {
  1886. return readInteger();
  1887. }
  1888. int InStream::readInt(int minv, int maxv, const std::string& variableName)
  1889. {
  1890. int result = readInt();
  1891. if (result < minv || result > maxv)
  1892. {
  1893. if (variableName.empty())
  1894. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1895. else
  1896. quit(_wa, ("Integer parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1897. }
  1898. return result;
  1899. }
  1900. int InStream::readInteger(int minv, int maxv, const std::string& variableName)
  1901. {
  1902. return readInt(minv, maxv, variableName);
  1903. }
  1904. double InStream::readReal()
  1905. {
  1906. if (!strict && seekEof())
  1907. quit(_pe, "Unexpected end of file - double expected");
  1908. return stringToDouble(*this, readWord().c_str());
  1909. }
  1910. double InStream::readDouble()
  1911. {
  1912. return readReal();
  1913. }
  1914. double InStream::readReal(double minv, double maxv, const std::string& variableName)
  1915. {
  1916. double result = readReal();
  1917. if (result < minv || result > maxv)
  1918. {
  1919. if (variableName.empty())
  1920. quit(_wa, ("Double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1921. else
  1922. quit(_wa, ("Double parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1923. }
  1924. return result;
  1925. }
  1926. double InStream::readDouble(double minv, double maxv, const std::string& variableName)
  1927. {
  1928. return readReal(minv, maxv, variableName);
  1929. }
  1930. double InStream::readStrictReal(double minv, double maxv,
  1931. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1932. const std::string& variableName)
  1933. {
  1934. if (!strict && seekEof())
  1935. quit(_pe, "Unexpected end of file - strict double expected");
  1936. double result = stringToStrictDouble(*this, readWord().c_str(),
  1937. minAfterPointDigitCount, maxAfterPointDigitCount);
  1938. if (result < minv || result > maxv)
  1939. {
  1940. if (variableName.empty())
  1941. quit(_wa, ("Strict double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1942. else
  1943. quit(_wa, ("Strict double parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1944. }
  1945. return result;
  1946. }
  1947. double InStream::readStrictDouble(double minv, double maxv,
  1948. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1949. const std::string& variableName)
  1950. {
  1951. return readStrictReal(minv, maxv,
  1952. minAfterPointDigitCount, maxAfterPointDigitCount,
  1953. variableName);
  1954. }
  1955. bool InStream::eof()
  1956. {
  1957. if (!strict && NULL == file)
  1958. return true;
  1959. return reader->eof();
  1960. }
  1961. bool InStream::seekEof()
  1962. {
  1963. if (NULL == file)
  1964. return true;
  1965. skipBlanks();
  1966. return eof();
  1967. }
  1968. bool InStream::eoln()
  1969. {
  1970. if (!strict && NULL == file)
  1971. return true;
  1972. int c = reader->nextChar();
  1973. if (!strict)
  1974. {
  1975. if (c == EOF)
  1976. return true;
  1977. if (c == CR)
  1978. {
  1979. c = reader->nextChar();
  1980. if (c != LF)
  1981. {
  1982. reader->unreadChar(CR);
  1983. reader->unreadChar(c);
  1984. return false;
  1985. }
  1986. else
  1987. return true;
  1988. }
  1989. if (c == LF)
  1990. return true;
  1991. reader->unreadChar(c);
  1992. return false;
  1993. }
  1994. else
  1995. {
  1996. bool returnCr = false;
  1997. #ifdef ON_WINDOWS
  1998. if (c != CR)
  1999. {
  2000. reader->unreadChar(c);
  2001. return false;
  2002. }
  2003. else
  2004. {
  2005. if (!returnCr)
  2006. returnCr = true;
  2007. c = reader->nextChar();
  2008. }
  2009. #endif
  2010. if (c != LF)
  2011. {
  2012. if (returnCr)
  2013. reader->unreadChar(CR);
  2014. reader->unreadChar(LF);
  2015. return false;
  2016. }
  2017. return true;
  2018. }
  2019. }
  2020. void InStream::readEoln()
  2021. {
  2022. if (!eoln())
  2023. quit(_pe, "Expected EOLN");
  2024. }
  2025. void InStream::readEof()
  2026. {
  2027. if (!eof())
  2028. quit(_pe, "Expected EOF");
  2029. if (TestlibFinalizeGuard::alive && this == &inf)
  2030. testlibFinalizeGuard.readEofCount++;
  2031. }
  2032. bool InStream::seekEoln()
  2033. {
  2034. if (NULL == file)
  2035. return true;
  2036. int cur;
  2037. do
  2038. {
  2039. cur = reader->nextChar();
  2040. }
  2041. while (cur == SPACE || cur == TAB);
  2042. reader->unreadChar(cur);
  2043. return eoln();
  2044. }
  2045. void InStream::nextLine()
  2046. {
  2047. readLine();
  2048. }
  2049. void InStream::readStringTo(std::string& result)
  2050. {
  2051. if (NULL == file)
  2052. quit(_pe, "Expected line");
  2053. result.clear();
  2054. int cur;
  2055. for (;;)
  2056. {
  2057. cur = reader->curChar();
  2058. if (isEoln(cur))
  2059. break;
  2060. if (cur == EOF)
  2061. break;
  2062. result += char(reader->nextChar());
  2063. }
  2064. if (strict)
  2065. readEoln();
  2066. else
  2067. eoln();
  2068. }
  2069. std::string InStream::readString()
  2070. {
  2071. readStringTo(_tmpReadToken);
  2072. return _tmpReadToken;
  2073. }
  2074. void InStream::readStringTo(std::string& result, const pattern& p, const std::string& variableName)
  2075. {
  2076. readStringTo(result);
  2077. if (!p.matches(result))
  2078. {
  2079. if (variableName.empty())
  2080. quit(_wa, ("Line \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2081. else
  2082. quit(_wa, ("Line [name=" + variableName + "] equals to \"" + __testlib_part(result) + "\", doesn't correspond to pattern \"" + p.src() + "\"").c_str());
  2083. }
  2084. }
  2085. void InStream::readStringTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  2086. {
  2087. readStringTo(result, pattern(ptrn), variableName);
  2088. }
  2089. std::string InStream::readString(const pattern& p, const std::string& variableName)
  2090. {
  2091. readStringTo(_tmpReadToken, p, variableName);
  2092. return _tmpReadToken;
  2093. }
  2094. std::string InStream::readString(const std::string& ptrn, const std::string& variableName)
  2095. {
  2096. readStringTo(_tmpReadToken, ptrn, variableName);
  2097. return _tmpReadToken;
  2098. }
  2099. void InStream::readLineTo(std::string& result)
  2100. {
  2101. readStringTo(result);
  2102. }
  2103. std::string InStream::readLine()
  2104. {
  2105. return readString();
  2106. }
  2107. void InStream::readLineTo(std::string& result, const pattern& p, const std::string& variableName)
  2108. {
  2109. readStringTo(result, p, variableName);
  2110. }
  2111. void InStream::readLineTo(std::string& result, const std::string& ptrn, const std::string& variableName)
  2112. {
  2113. readStringTo(result, ptrn, variableName);
  2114. }
  2115. std::string InStream::readLine(const pattern& p, const std::string& variableName)
  2116. {
  2117. return readString(p, variableName);
  2118. }
  2119. std::string InStream::readLine(const std::string& ptrn, const std::string& variableName)
  2120. {
  2121. return readString(ptrn, variableName);
  2122. }
  2123. void InStream::close()
  2124. {
  2125. if (opened)
  2126. fclose(file);
  2127. if (NULL != reader)
  2128. {
  2129. delete reader;
  2130. reader = NULL;
  2131. }
  2132. opened = false;
  2133. }
  2134. #ifdef __GNUC__
  2135. __attribute__ ((noreturn))
  2136. #endif
  2137. NORETURN void quit(TResult result, const std::string& msg)
  2138. {
  2139. ouf.quit(result, msg.c_str());
  2140. }
  2141. #ifdef __GNUC__
  2142. __attribute__ ((noreturn))
  2143. #endif
  2144. NORETURN void quit(TResult result, const char* msg)
  2145. {
  2146. ouf.quit(result, msg);
  2147. }
  2148. #ifdef __GNUC__
  2149. __attribute__ ((noreturn))
  2150. #endif
  2151. NORETURN void __testlib_quitp(double points, const char* message)
  2152. {
  2153. __testlib_points = points;
  2154. char buffer[512];
  2155. if (NULL == message || 0 == strlen(message))
  2156. std::sprintf(buffer, "%.10f", points);
  2157. else
  2158. std::sprintf(buffer, "%.10f %s", points, message);
  2159. quit(_points, buffer);
  2160. }
  2161. #ifdef __GNUC__
  2162. __attribute__ ((noreturn))
  2163. #endif
  2164. NORETURN void quitp(float points, const std::string& message = "")
  2165. {
  2166. __testlib_quitp(double(points), message.c_str());
  2167. }
  2168. #ifdef __GNUC__
  2169. __attribute__ ((noreturn))
  2170. #endif
  2171. NORETURN void quitp(double points, const std::string& message = "")
  2172. {
  2173. __testlib_quitp(points, message.c_str());
  2174. }
  2175. #ifdef __GNUC__
  2176. __attribute__ ((noreturn))
  2177. #endif
  2178. NORETURN void quitp(long double points, const std::string& message = "")
  2179. {
  2180. __testlib_quitp(double(points), message.c_str());
  2181. }
  2182. template<typename F>
  2183. #ifdef __GNUC__
  2184. __attribute__ ((format (printf, 2, 3)))
  2185. __attribute__ ((noreturn))
  2186. #endif
  2187. NORETURN void quitp(F points, const char* format, ...)
  2188. {
  2189. FMT_TO_RESULT(format, format, message);
  2190. quitp(points, message);
  2191. }
  2192. #ifdef __GNUC__
  2193. __attribute__ ((format (printf, 2, 3)))
  2194. __attribute__ ((noreturn))
  2195. #endif
  2196. NORETURN void quitf(TResult result, const char* format, ...)
  2197. {
  2198. FMT_TO_RESULT(format, format, message);
  2199. quit(result, message);
  2200. }
  2201. #ifdef __GNUC__
  2202. __attribute__ ((format (printf, 3, 4)))
  2203. #endif
  2204. void quitif(bool condition, TResult result, const char* format, ...)
  2205. {
  2206. if (condition)
  2207. {
  2208. FMT_TO_RESULT(format, format, message);
  2209. quit(result, message);
  2210. }
  2211. }
  2212. #ifdef __GNUC__
  2213. __attribute__ ((noreturn))
  2214. #endif
  2215. NORETURN void __testlib_help()
  2216. {
  2217. InStream::textColor(InStream::LightCyan);
  2218. std::fprintf(stderr, "TESTLIB %s, http://code.google.com/p/testlib/ ", VERSION);
  2219. std::fprintf(stderr, "by Mike Mirzayanov, copyright(c) 2005-2013\n");
  2220. std::fprintf(stderr, "Checker name: \"%s\"\n", checkerName.c_str());
  2221. InStream::textColor(InStream::LightGray);
  2222. std::fprintf(stderr, "\n");
  2223. std::fprintf(stderr, "Latest features: \n");
  2224. for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char*); i++)
  2225. {
  2226. std::fprintf(stderr, "*) %s\n", latestFeatures[i]);
  2227. }
  2228. std::fprintf(stderr, "\n");
  2229. std::fprintf(stderr, "Program must be run with the following arguments: \n");
  2230. std::fprintf(stderr, " <input-file> <output-file> <answer-file> [<report-file> [<-appes>]]\n\n");
  2231. std::exit(0);
  2232. }
  2233. void registerGen(int argc, char* argv[])
  2234. {
  2235. testlibMode = _generator;
  2236. __testlib_set_binary(stdin);
  2237. rnd.setSeed(argc, argv);
  2238. }
  2239. void registerInteraction(int argc, char* argv[])
  2240. {
  2241. testlibMode = _interactor;
  2242. __testlib_set_binary(stdin);
  2243. if (argc > 1 && !strcmp("--help", argv[1]))
  2244. __testlib_help();
  2245. // testlib assumes: sizeof(int) = 4.
  2246. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  2247. // testlib assumes: INT_MAX == 2147483647.
  2248. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  2249. // testlib assumes: sizeof(long long) = 8.
  2250. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  2251. if (argc < 3 || argc > 6)
  2252. {
  2253. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2254. std::string("<input-file> <output-file> [<answer-file> [<report-file> [<-appes>]]]") +
  2255. "\nUse \"--help\" to get help information");
  2256. }
  2257. if (argc <= 4)
  2258. {
  2259. resultName = "";
  2260. appesMode = false;
  2261. }
  2262. if (argc == 5)
  2263. {
  2264. resultName = argv[4];
  2265. appesMode = false;
  2266. }
  2267. if (argc == 6)
  2268. {
  2269. if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5]))
  2270. {
  2271. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2272. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  2273. }
  2274. else
  2275. {
  2276. resultName = argv[4];
  2277. appesMode = true;
  2278. }
  2279. }
  2280. if (setvbuf(stdin, NULL, _IONBF, 0) != 0)
  2281. quit(_fail, std::string("Can not disable buffer for stdin"));
  2282. if (setvbuf(stdout, NULL, _IONBF, 0) != 0)
  2283. quit(_fail, std::string("Can not disable buffer for stdout"));
  2284. if (setvbuf(stderr, NULL, _IONBF, 0) != 0)
  2285. quit(_fail, std::string("Can not disable buffer for stderr"));
  2286. inf.init(argv[1], _input);
  2287. tout.open(argv[2], std::ios_base::out);
  2288. if (tout.fail() || !tout.is_open())
  2289. quit(_fail, std::string("Can not write to the test-output-file '") + argv[2] + std::string("'"));
  2290. ouf.init(stdin, _output);
  2291. if (argc >= 4)
  2292. ans.init(argv[3], _answer);
  2293. }
  2294. void registerValidation()
  2295. {
  2296. testlibMode = _validator;
  2297. __testlib_set_binary(stdin);
  2298. // testlib assumes: sizeof(int) = 4.
  2299. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  2300. // testlib assumes: INT_MAX == 2147483647.
  2301. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  2302. // testlib assumes: sizeof(long long) = 8.
  2303. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  2304. inf.init(stdin, _input);
  2305. inf.strict = true;
  2306. }
  2307. void registerTestlibCmd(int argc, char* argv[])
  2308. {
  2309. testlibMode = _checker;
  2310. __testlib_set_binary(stdin);
  2311. if (argc > 1 && !strcmp("--help", argv[1]))
  2312. __testlib_help();
  2313. // testlib assumes: sizeof(int) = 4.
  2314. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  2315. // testlib assumes: INT_MAX == 2147483647.
  2316. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  2317. // testlib assumes: sizeof(long long) = 8.
  2318. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  2319. if (argc < 4 || argc > 6)
  2320. {
  2321. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2322. std::string("<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]") +
  2323. "\nUse \"--help\" to get help information");
  2324. }
  2325. if (argc == 4)
  2326. {
  2327. resultName = "";
  2328. appesMode = false;
  2329. }
  2330. if (argc == 5)
  2331. {
  2332. resultName = argv[4];
  2333. appesMode = false;
  2334. }
  2335. if (argc == 6)
  2336. {
  2337. if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5]))
  2338. {
  2339. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2340. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  2341. }
  2342. else
  2343. {
  2344. resultName = argv[4];
  2345. appesMode = true;
  2346. }
  2347. }
  2348. inf.init(argv[1], _input);
  2349. ouf.init(argv[2], _output);
  2350. ans.init(argv[3], _answer);
  2351. }
  2352. void registerTestlib(int argc, ...)
  2353. {
  2354. if (argc < 3 || argc > 5)
  2355. quit(_fail, std::string("Program must be run with the following arguments: ") +
  2356. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  2357. char** argv = new char*[argc + 1];
  2358. va_list ap;
  2359. va_start(ap, argc);
  2360. argv[0] = NULL;
  2361. for (int i = 0; i < argc; i++)
  2362. {
  2363. argv[i + 1] = va_arg(ap, char*);
  2364. }
  2365. va_end(ap);
  2366. registerTestlibCmd(argc + 1, argv);
  2367. delete[] argv;
  2368. }
  2369. inline bool isNaN(double r)
  2370. {
  2371. return ((r != r) == true) && ((r == r) == false) && ((1.0 > r) == false) && ((1.0 < r) == false);
  2372. }
  2373. inline bool isInfinite(double r)
  2374. {
  2375. return (r > 1E100 || r < -1E100);
  2376. }
  2377. #ifdef __GNUC__
  2378. __attribute__((const))
  2379. #endif
  2380. inline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)
  2381. {
  2382. if (isNaN(expected))
  2383. {
  2384. return isNaN(result);
  2385. }
  2386. else
  2387. if (isInfinite(expected))
  2388. {
  2389. if (expected > 0)
  2390. {
  2391. return result > 0 && isInfinite(result);
  2392. }
  2393. else
  2394. {
  2395. return result < 0 && isInfinite(result);
  2396. }
  2397. }
  2398. else
  2399. if (isNaN(result) || isInfinite(result))
  2400. {
  2401. return false;
  2402. }
  2403. else
  2404. if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR + 1E-15)
  2405. {
  2406. return true;
  2407. }
  2408. else
  2409. {
  2410. double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),
  2411. expected * (1.0 + MAX_DOUBLE_ERROR));
  2412. double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),
  2413. expected * (1.0 + MAX_DOUBLE_ERROR));
  2414. return result + 1E-15 >= minv && result <= maxv + 1E-15;
  2415. }
  2416. }
  2417. #ifdef __GNUC__
  2418. __attribute__((const))
  2419. #endif
  2420. inline double doubleDelta(double expected, double result)
  2421. {
  2422. double absolute = __testlib_abs(result - expected);
  2423. if (__testlib_abs(expected) > 1E-9)
  2424. {
  2425. double relative = __testlib_abs(absolute / expected);
  2426. return __testlib_min(absolute, relative);
  2427. }
  2428. else
  2429. return absolute;
  2430. }
  2431. static inline void __testlib_ensure(bool cond, const std::string& msg)
  2432. {
  2433. if (!cond)
  2434. quit(_fail, msg.c_str());
  2435. }
  2436. static inline void __testlib_ensure(bool cond, const char* msg)
  2437. {
  2438. if (!cond)
  2439. quit(_fail, msg);
  2440. }
  2441. #define ensure(cond) __testlib_ensure(cond, "Condition failed: \"" #cond "\"")
  2442. #ifdef __GNUC__
  2443. __attribute__ ((format (printf, 2, 3)))
  2444. #endif
  2445. inline void ensuref(bool cond, const char* format, ...)
  2446. {
  2447. if (!cond)
  2448. {
  2449. FMT_TO_RESULT(format, format, message);
  2450. __testlib_ensure(cond, message);
  2451. }
  2452. }
  2453. #ifdef __GNUC__
  2454. __attribute__((noreturn))
  2455. #endif
  2456. NORETURN static void __testlib_fail(const std::string& message)
  2457. {
  2458. quitf(_fail, "%s", message.c_str());
  2459. }
  2460. #ifdef __GNUC__
  2461. __attribute__ ((format (printf, 1, 2)))
  2462. #endif
  2463. void setName(const char* format, ...)
  2464. {
  2465. FMT_TO_RESULT(format, format, name);
  2466. checkerName = name;
  2467. }
  2468. /*
  2469. * Do not use random_shuffle, because it will produce different result
  2470. * for different C++ compilers.
  2471. *
  2472. * This implementation uses testlib random_t to produce random numbers, so
  2473. * it is stable.
  2474. */
  2475. template<typename _RandomAccessIter>
  2476. void shuffle(_RandomAccessIter __first, _RandomAccessIter __last)
  2477. {
  2478. if (__first == __last) return;
  2479. for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)
  2480. std::iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));
  2481. }
  2482. template<typename _RandomAccessIter>
  2483. #ifdef __GNUC__
  2484. __attribute__ ((error("Don't use random_shuffle(), use shuffle() instead")))
  2485. #endif
  2486. void random_shuffle(_RandomAccessIter , _RandomAccessIter )
  2487. {
  2488. quitf(_fail, "Don't use random_shuffle(), use shuffle() instead");
  2489. }
  2490. #ifdef __GLIBC__
  2491. # define RAND_THROW_STATEMENT throw()
  2492. #else
  2493. # define RAND_THROW_STATEMENT
  2494. #endif
  2495. #ifdef __GNUC__
  2496. __attribute__ ((error("Don't use rand(), use rnd.next() instead")))
  2497. #endif
  2498. int rand() RAND_THROW_STATEMENT
  2499. {
  2500. quitf(_fail, "Don't use rand(), use rnd.next() instead");
  2501. /* This line never runs. */
  2502. //throw "Don't use rand(), use rnd.next() instead";
  2503. }
  2504. #ifdef __GNUC__
  2505. __attribute__ ((error("Don't use srand(), you should use "
  2506. "'registerGen(argc, argv);' to initialize generator seed "
  2507. "by hash code of the command line params")))
  2508. #endif
  2509. void srand(unsigned int seed) RAND_THROW_STATEMENT
  2510. {
  2511. quitf(_fail, "Don't use srand(), you should use "
  2512. "'registerGen(argc, argv);' to initialize generator seed "
  2513. "by hash code of the command line params [seed=%d ignored]", seed);
  2514. }
  2515. void startTest(int test)
  2516. {
  2517. const std::string testFileName = vtos(test);
  2518. if (NULL == freopen(testFileName.c_str(), "wt", stdout))
  2519. __testlib_fail("Unable to write file '" + testFileName + "'");
  2520. }
  2521. #ifdef __GNUC__
  2522. __attribute__ ((format (printf, 1, 2)))
  2523. #endif
  2524. std::string format(const char* fmt, ...)
  2525. {
  2526. FMT_TO_RESULT(fmt, fmt, result);
  2527. return result;
  2528. }
  2529. std::string format(const std::string& fmt, ...)
  2530. {
  2531. FMT_TO_RESULT(fmt, fmt.c_str(), result);
  2532. return result;
  2533. }
  2534. inline std::string upperCase(std::string s)
  2535. {
  2536. for (size_t i = 0; i < s.length(); i++)
  2537. if ('a' <= s[i] && s[i] <= 'z')
  2538. s[i] = char(s[i] - 'a' + 'A');
  2539. return s;
  2540. }
  2541. inline std::string lowerCase(std::string s)
  2542. {
  2543. for (size_t i = 0; i < s.length(); i++)
  2544. if ('A' <= s[i] && s[i] <= 'Z')
  2545. s[i] = char(s[i] - 'A' + 'a');
  2546. return s;
  2547. }
  2548. inline std::string compress(const std::string& s)
  2549. {
  2550. return __testlib_part(s);
  2551. }
  2552. inline std::string englishEnding(int x)
  2553. {
  2554. x %= 100;
  2555. if (x / 10 == 1)
  2556. return "th";
  2557. if (x % 10 == 1)
  2558. return "st";
  2559. if (x % 10 == 2)
  2560. return "nd";
  2561. if (x % 10 == 3)
  2562. return "rd";
  2563. return "th";
  2564. }
  2565. inline std::string trim(const std::string& s)
  2566. {
  2567. if (s.empty())
  2568. return s;
  2569. int left = 0;
  2570. while (left < int(s.length()) && isBlanks(s[left]))
  2571. left++;
  2572. if (left >= int(s.length()))
  2573. return "";
  2574. int right = int(s.length()) - 1;
  2575. while (right >= 0 && isBlanks(s[right]))
  2576. right--;
  2577. if (right < 0)
  2578. return "";
  2579. return s.substr(left, right - left + 1);
  2580. }
  2581. #endif