testlib.h 71 KB

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