testlib.h 71 KB

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