testlib.h 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983
  1. #ifndef _TESTLIB_H_
  2. #define _TESTLIB_H_
  3. /*
  4. *
  5. * Copyright (c) 2005-2009
  6. */
  7. #define VERSION "0.6.1.1"
  8. /*
  9. * Mike Mirzayanov
  10. *
  11. * This material is provided "as is", with absolutely no warranty expressed
  12. * or implied. Any use is at your own risk.
  13. *
  14. * Permission to use or copy this software for any purpose is hereby granted
  15. * without fee, provided the above notices are retained on all copies.
  16. * Permission to modify the code and to distribute modified code is granted,
  17. * provided the above notices are retained, and a notice that the code was
  18. * modified is included with the above copyright notice.
  19. *
  20. */
  21. /* NOTE: This file contains testlib library for C++.
  22. *
  23. * Check, using testlib running format:
  24. * check.exe <Input_File> <Output_File> <Answer_File> [<Result_File> [-appes]],
  25. * If result file is specified it will contain results.
  26. *
  27. * Validator, using testlib running format:
  28. * validator.exe < input.txt,
  29. * It will return non-zero exit code and writes message to standard output.
  30. *
  31. * Generator, using testlib running format:
  32. * gen.exe [parameter-1] [parameter-2] [... paramerter-n],
  33. * You can write generated test(s) into standard output or into the file(s).
  34. */
  35. const char* latestFeatures[] = {
  36. "Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode",
  37. "Package extended with samples of generators and validators",
  38. "Written the documentation for classes and public methods in testlib.h",
  39. "Implemented random routine to support generators, use registerGen() to switch it on",
  40. "Implemented strict mode to validate tests, use registerValidation() to switch it on",
  41. "Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output",
  42. "Added InStream::readLong() and removed InStream::readLongint()",
  43. "Now no footer added to each report by default (use directive FOOTER to switch on)",
  44. "Now every checker has a name, use setName(const char* format, ...) to set it",
  45. "Now it is compatible with TTS (by Kittens Computing)",
  46. "Added \'ensure(condition, message = \"\")\' feature, it works like assert()",
  47. "Fixed compatibility with MS C++ 7.1",
  48. "Added footer with exit code information",
  49. "Added compatibility with EJUDGE (compile with EJUDGE directive)"
  50. };
  51. #ifdef _MSC_VER
  52. #define _CRT_SECURE_NO_DEPRECATE
  53. #define _CRT_SECURE_NO_WARNINGS
  54. #endif
  55. #define random __random_depricated
  56. #include <stdlib.h>
  57. #include <climits>
  58. #undef random
  59. #include <cstdio>
  60. #include <cctype>
  61. #include <string>
  62. #include <vector>
  63. #include <set>
  64. #include <cmath>
  65. #include <sstream>
  66. #include <algorithm>
  67. #include <cstring>
  68. #include <stdarg.h>
  69. #include <fcntl.h>
  70. #if !defined(unix)
  71. #include <io.h>
  72. #endif
  73. #if ( _WIN32 || __WIN32__ || _WIN64 || __WIN64__ )
  74. #include <windows.h>
  75. #define ON_WINDOWS
  76. #else
  77. #define WORD unsigned short
  78. #endif
  79. #ifndef LLONG_MIN
  80. #define LLONG_MIN (-9223372036854775807LL - 1)
  81. #endif
  82. #define MAX_FORMAT_BUFFER_SIZE (2097152)
  83. #define LF ((char)10)
  84. #define CR ((char)13)
  85. #define TAB ((char)9)
  86. #define SPACE ((char)' ')
  87. #define EOFC ((char)26)
  88. #ifndef EJUDGE
  89. #define OK_EXIT_CODE 0
  90. #define WA_EXIT_CODE 1
  91. #define PE_EXIT_CODE 2
  92. #define FAIL_EXIT_CODE 3
  93. #define DIRT_EXIT_CODE 4
  94. #else
  95. #define OK_EXIT_CODE 0
  96. #define WA_EXIT_CODE 5
  97. #define PE_EXIT_CODE 4
  98. #define FAIL_EXIT_CODE 6
  99. #define DIRT_EXIT_CODE 6
  100. #endif
  101. #define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition != 0) * 2 - 1];
  102. template<typename T>
  103. static inline T __testlib_abs(const T& x)
  104. {
  105. return x > 0 ? x : -x;
  106. }
  107. template<typename T>
  108. static inline T __testlib_min(const T& a, const T& b)
  109. {
  110. return a < b ? a : b;
  111. }
  112. template<typename T>
  113. static inline T __testlib_max(const T& a, const T& b)
  114. {
  115. return a > b ? a : b;
  116. }
  117. /*
  118. * Very simple regex-like pattern.
  119. * It used for two purposes: validation and generation.
  120. *
  121. * For example, pattern("[a-z]{1,5}").next(rnd) will return
  122. * random string from lowercase latin letters with length
  123. * from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}")
  124. * for the same effect.
  125. *
  126. * Another samples:
  127. * "mike|john" will generate (match) "mike" or "john";
  128. * "-?[1-9][0-9]{0,3}" will generate (match) non-zero integers from -9999 to 9999;
  129. * "id-([ac]|b{2})" will generate (match) "id-a", "id-bb", "id-c";
  130. * "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't
  131. * use it for generations.
  132. *
  133. * You can't use pattern for generation if it contains meta-symbol '*'. Also it
  134. * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].
  135. *
  136. * For matching very simple greedy algorithm is used. For example, pattern
  137. * "[0-9]?1" will not match "1", because of greedy nature of matching.
  138. * Alternations (meta-symbols "|") are processed with brute-force algorithm, so
  139. * do not use many alternations in one expression.
  140. *
  141. * If you want to use one expression many times it is better to compile it into
  142. * a single pattern like "pattern p("[a-z]+")". Later you can use
  143. * "p.matches(std::string s)" or "p.next(random& rd)" to check matching or generate
  144. * new string by pattern.
  145. *
  146. * Simpler way to read token and check it for pattern matching is "inf.readToken("[a-z]+")".
  147. */
  148. class random;
  149. class pattern
  150. {
  151. public:
  152. /* Create pattern instance by string. */
  153. pattern(std::string s);
  154. /* Generate new string by pattern and given random. */
  155. std::string next(random& rnd) const;
  156. /* Checks if given string match the pattern. */
  157. bool matches(const std::string& s) const;
  158. private:
  159. bool matches(const std::string& s, size_t pos) const;
  160. std::vector<pattern> children;
  161. std::vector<char> chars;
  162. int from;
  163. int to;
  164. };
  165. /*
  166. * Use random instances to generate random values. It is preffered
  167. * way to use randoms instead of rand() function or self-written
  168. * randoms.
  169. *
  170. * Testlib defines global variable "rnd" of random class.
  171. * Use registerGen(argc, argv) to setup random seed be command
  172. * line.
  173. *
  174. * Random generates uniformly distributed values if another strategy is
  175. * not specified explicitly.
  176. */
  177. class random
  178. {
  179. private:
  180. long long seed;
  181. static const long long multiplier;
  182. static const long long addend;
  183. static const long long mask;
  184. static const int lim;
  185. long long nextBits(int bits)
  186. {
  187. if (bits <= 48)
  188. {
  189. seed = (seed * multiplier + addend) & mask;
  190. return (long long)(seed >> (48 - bits));
  191. }
  192. else
  193. {
  194. if (bits > 63)
  195. throw "n must be less than 64";
  196. return ((nextBits(31) << 32) ^ nextBits(31));
  197. }
  198. }
  199. public:
  200. /* New random with fixed seed. */
  201. random()
  202. : seed(3905348978240129619LL)
  203. {
  204. }
  205. /* Sets seed by command line. */
  206. void setSeed(int argc, char* argv[])
  207. {
  208. random p;
  209. seed = 3905348978240129619LL;
  210. for (int i = 1; i < argc; i++)
  211. {
  212. std::size_t le = std::strlen(argv[i]);
  213. for (std::size_t j = 0; j < le; j++)
  214. seed = seed * multiplier * (unsigned int)(argv[i][j]) + addend;
  215. seed += multiplier / addend;
  216. }
  217. seed = seed & mask;
  218. }
  219. /* Sets seed by given value. */
  220. void setSeed(long long _seed)
  221. {
  222. _seed = (_seed ^ multiplier) & mask;
  223. seed = _seed;
  224. }
  225. /* Random value in range [0, n-1]. */
  226. int next(int n)
  227. {
  228. if (n <= 0)
  229. throw "n must be positive";
  230. if ((n & -n) == n) // n is a power of 2
  231. return (int)((n * (long long)nextBits(31)) >> 31);
  232. int bits, val;
  233. do
  234. {
  235. bits = int(nextBits(31));
  236. val = bits % n;
  237. } while (bits - val + (n - 1) < 0);
  238. return val;
  239. }
  240. /* Random value in range [0, n-1]. */
  241. int next(unsigned int n)
  242. {
  243. if (n >= INT_MAX)
  244. throw "n must be less INT_MAX";
  245. return next(int(n));
  246. }
  247. /* Random value in range [0, n-1]. */
  248. long long next(long long n)
  249. {
  250. if (n <= 0)
  251. throw "n must be positive";
  252. long long bits, val;
  253. do
  254. {
  255. bits = nextBits(63);
  256. val = bits % n;
  257. } while (bits - val + (n - 1) < 0);
  258. return val;
  259. }
  260. /* Returns random value in range [from,to]. */
  261. int next(int from, int to)
  262. {
  263. return next(to - from + 1) + from;
  264. }
  265. /* Returns random value in range [from,to]. */
  266. int next(unsigned int from, unsigned int to)
  267. {
  268. return next(to - from + 1) + from;
  269. }
  270. /* Returns random value in range [from,to]. */
  271. long long next(long long from, long long to)
  272. {
  273. return next(to - from + 1) + from;
  274. }
  275. /* Random double value in range [0, 1). */
  276. double next()
  277. {
  278. return (((long long)(nextBits(26)) << 27) + nextBits(27)) / (double)(1LL << 53);
  279. }
  280. /* Random double value in range [0, n). */
  281. double next(double n)
  282. {
  283. return n * next();
  284. }
  285. /* Random double value in range [from, to). */
  286. double next(double from, double to)
  287. {
  288. return next(to - from) + from;
  289. }
  290. /* Random string value by given pattern (see pattern documentation). */
  291. std::string next(const std::string& ptrn)
  292. {
  293. pattern p(ptrn);
  294. return p.next(*this);
  295. }
  296. /* Random string value by given pattern (see pattern documentation). */
  297. std::string next(const char* format, ...)
  298. {
  299. char* buffer = new char [MAX_FORMAT_BUFFER_SIZE];
  300. va_list ap;
  301. va_start(ap, format);
  302. std::vsprintf(buffer, format, ap);
  303. va_end(ap);
  304. std::string ptrn(buffer);
  305. delete[] buffer;
  306. return next(ptrn);
  307. }
  308. /*
  309. * Weighted next. If type == 0 than it is usual "next()".
  310. *
  311. * If type = 1, than it returns "max(next(), next())"
  312. * (the number of "max" functions equals to "type").
  313. *
  314. * If type < 0, than "max" function replaces with "min".
  315. */
  316. int wnext(int n, int type)
  317. {
  318. if (n <= 0)
  319. throw "n must be positive";
  320. if (abs(type) < random::lim)
  321. {
  322. int result = next(n);
  323. for (int i = 0; i < +type; i++)
  324. result = __testlib_max(result, next(n));
  325. for (int i = 0; i < -type; i++)
  326. result = __testlib_min(result, next(n));
  327. return result;
  328. }
  329. else
  330. {
  331. double p;
  332. if (type > 0)
  333. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  334. else
  335. p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));
  336. return int(n * p);
  337. }
  338. }
  339. /* See wnext(int, int). It uses the same algorithms. */
  340. int wnext(unsigned int n, int type)
  341. {
  342. if (n >= INT_MAX)
  343. throw "n must be less INT_MAX";
  344. return wnext(int(n), type);
  345. }
  346. /* See wnext(int, int). It uses the same algorithms. */
  347. long long wnext(long long n, int type)
  348. {
  349. if (n <= 0)
  350. throw "n must be positive";
  351. if (abs(type) < random::lim)
  352. {
  353. long long result = next(n);
  354. for (int i = 0; i < +type; i++)
  355. result = __testlib_max(result, next(n));
  356. for (int i = 0; i < -type; i++)
  357. result = __testlib_min(result, next(n));
  358. return result;
  359. }
  360. else
  361. {
  362. double p;
  363. if (type > 0)
  364. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  365. else
  366. p = std::pow(next() + 0.0, - type + 1);
  367. return (long long)(n * p);
  368. }
  369. }
  370. /* See wnext(int, int). It uses the same algorithms. */
  371. double wnext(int type)
  372. {
  373. if (abs(type) < random::lim)
  374. {
  375. double result = next();
  376. for (int i = 0; i < +type; i++)
  377. result = __testlib_max(result, next());
  378. for (int i = 0; i < -type; i++)
  379. result = __testlib_min(result, next());
  380. return result;
  381. }
  382. else
  383. {
  384. double p;
  385. if (type > 0)
  386. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  387. else
  388. p = std::pow(next() + 0.0, - type + 1);
  389. return p;
  390. }
  391. }
  392. /* See wnext(int, int). It uses the same algorithms. */
  393. double wnext(double n, int type)
  394. {
  395. if (n <= 0)
  396. throw "n must be positive";
  397. if (abs(type) < random::lim)
  398. {
  399. double result = next();
  400. for (int i = 0; i < +type; i++)
  401. result = __testlib_max(result, next());
  402. for (int i = 0; i < -type; i++)
  403. result = __testlib_min(result, next());
  404. return n * result;
  405. }
  406. else
  407. {
  408. double p;
  409. if (type > 0)
  410. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  411. else
  412. p = std::pow(next() + 0.0, - type + 1);
  413. return n * p;
  414. }
  415. }
  416. /* Returns weighted random value in range [from, to]. */
  417. int wnext(int from, int to, int type)
  418. {
  419. return wnext(to - from + 1, type) + from;
  420. }
  421. /* Returns weighted random value in range [from, to]. */
  422. int wnext(unsigned int from, unsigned int to, int type)
  423. {
  424. return wnext(to - from + 1, type) + from;
  425. }
  426. /* Returns weighted random value in range [from, to]. */
  427. long long wnext(long long from, long long to, int type)
  428. {
  429. return wnext(to - from + 1, type) + from;
  430. }
  431. /* Returns weighted random double value in range [from, to). */
  432. double wnext(double from, double to, int type)
  433. {
  434. return wnext(to - from, type) + from;
  435. }
  436. };
  437. const int random::lim = 25;
  438. const long long random::multiplier = 0x5DEECE66DLL;
  439. const long long random::addend = 0xBLL;
  440. const long long random::mask = (1LL << 48) - 1;
  441. /* Pattern implementation */
  442. bool pattern::matches(const std::string& s) const
  443. {
  444. return matches(s, 0);
  445. }
  446. static bool __pattern_isSlash(const std::string& s, size_t pos)
  447. {
  448. return s[pos] == '\\';
  449. }
  450. static bool __pattern_isCommandChar(const std::string& s, size_t pos, char value)
  451. {
  452. if (pos >= s.length())
  453. return false;
  454. int slashes = 0;
  455. int before = pos - 1;
  456. while (before >= 0 && s[before] == '\\')
  457. before--, slashes++;
  458. return slashes % 2 == 0 && s[pos] == value;
  459. }
  460. static char __pattern_getChar(const std::string& s, size_t& pos)
  461. {
  462. if (__pattern_isSlash(s, pos))
  463. pos += 2;
  464. else
  465. pos++;
  466. return s[pos - 1];
  467. }
  468. static int __pattern_greedyMatch(const std::string& s, size_t pos, const std::vector<char> chars)
  469. {
  470. int result = 0;
  471. while (pos < s.length())
  472. {
  473. char c = __pattern_getChar(s, pos);
  474. if (!std::binary_search(chars.begin(), chars.end(), c))
  475. break;
  476. else
  477. result++;
  478. }
  479. return result;
  480. }
  481. bool pattern::matches(const std::string& s, size_t pos) const
  482. {
  483. std::string result;
  484. if (to > 0)
  485. {
  486. int size = __pattern_greedyMatch(s, pos, chars);
  487. if (size < from)
  488. return false;
  489. if (size > to)
  490. size = to;
  491. pos += size;
  492. }
  493. if (children.size() > 0)
  494. {
  495. for (size_t child = 0; child < children.size(); child++)
  496. if (children[child].matches(s, pos))
  497. return true;
  498. return false;
  499. }
  500. else
  501. return pos == s.length();
  502. }
  503. std::string pattern::next(random& rnd) const
  504. {
  505. std::string result;
  506. if (to == INT_MAX)
  507. throw "Can't process character '*' for generation";
  508. if (to > 0)
  509. {
  510. int count = rnd.next(to - from + 1) + from;
  511. for (int i = 0; i < count; i++)
  512. result += chars[rnd.next(int(chars.size()))];
  513. }
  514. if (children.size() > 0)
  515. {
  516. int child = rnd.next(int(children.size()));
  517. result += children[child].next(rnd);
  518. }
  519. return result;
  520. }
  521. static void __pattern_scanCounts(const std::string& s, size_t& pos, int& from, int& to)
  522. {
  523. if (pos >= s.length())
  524. {
  525. from = to = 1;
  526. return;
  527. }
  528. if (__pattern_isCommandChar(s, pos, '{'))
  529. {
  530. std::vector<std::string> parts;
  531. std::string part;
  532. pos++;
  533. while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))
  534. {
  535. if (__pattern_isCommandChar(s, pos, ','))
  536. parts.push_back(part), part = "", pos++;
  537. else
  538. part += __pattern_getChar(s, pos);
  539. }
  540. if (part != "")
  541. parts.push_back(part);
  542. if (!__pattern_isCommandChar(s, pos, '}'))
  543. throw "Illegal pattern";
  544. pos++;
  545. if (parts.size() < 1 || parts.size() > 2)
  546. throw "Illegal pattern";
  547. std::vector<int> numbers;
  548. for (size_t i = 0; i < parts.size(); i++)
  549. {
  550. if (parts[i].length() == 0)
  551. throw "Illegal pattern";
  552. int number;
  553. if (std::sscanf(parts[i].c_str(), "%d", &number) != 1)
  554. throw "Illegal pattern";
  555. numbers.push_back(number);
  556. }
  557. if (numbers.size() == 1)
  558. from = to = numbers[0];
  559. else
  560. from = numbers[0], to = numbers[1];
  561. if (from > to)
  562. throw "Illegal pattern";
  563. }
  564. else
  565. {
  566. if (__pattern_isCommandChar(s, pos, '?'))
  567. {
  568. from = 0, to = 1, pos++;
  569. return;
  570. }
  571. if (__pattern_isCommandChar(s, pos, '*'))
  572. {
  573. from = 0, to = INT_MAX, pos++;
  574. return;
  575. }
  576. if (__pattern_isCommandChar(s, pos, '+'))
  577. {
  578. from = 1, to = INT_MAX, pos++;
  579. return;
  580. }
  581. from = to = 1;
  582. }
  583. }
  584. static std::vector<char> __pattern_scanCharSet(const std::string& s, size_t& pos)
  585. {
  586. if (pos >= s.length())
  587. throw "Illegal pattern";
  588. std::vector<char> result;
  589. if (__pattern_isCommandChar(s, pos, '['))
  590. {
  591. pos++;
  592. bool negative = __pattern_isCommandChar(s, pos, '^');
  593. char prev = 0;
  594. while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))
  595. {
  596. if (__pattern_isCommandChar(s, pos, '-') && prev != 0)
  597. {
  598. pos++;
  599. if (pos + 1 == s.length())
  600. {
  601. result.push_back(prev);
  602. prev = '-';
  603. continue;
  604. }
  605. char next = __pattern_getChar(s, pos);
  606. if (prev > next)
  607. throw "Illegal pattern";
  608. for (char c = prev; c <= next; c++)
  609. result.push_back(c);
  610. prev = 0;
  611. }
  612. else
  613. {
  614. if (prev != 0)
  615. result.push_back(prev);
  616. prev = __pattern_getChar(s, pos);
  617. }
  618. }
  619. if (prev != 0)
  620. result.push_back(prev);
  621. if (!__pattern_isCommandChar(s, pos, ']'))
  622. throw "Illegal pattern";
  623. pos++;
  624. if (negative)
  625. {
  626. std::sort(result.begin(), result.end());
  627. std::vector<char> actuals;
  628. for (int code = 0; code < 255; code++)
  629. {
  630. char c = char(code);
  631. if (!std::binary_search(result.begin(), result.end(), c))
  632. actuals.push_back(c);
  633. }
  634. result = actuals;
  635. }
  636. std::sort(result.begin(), result.end());
  637. }
  638. else
  639. result.push_back(__pattern_getChar(s, pos));
  640. return result;
  641. }
  642. pattern::pattern(std::string s): from(0), to(0)
  643. {
  644. std::string t;
  645. for (size_t i = 0; i < s.length(); i++)
  646. if (!__pattern_isCommandChar(s, i, ' '))
  647. t += s[i];
  648. s = t;
  649. int opened = 0;
  650. int firstClose = -1;
  651. std::vector<int> seps;
  652. for (size_t i = 0; i < s.length(); i++)
  653. {
  654. if (__pattern_isCommandChar(s, i, '('))
  655. {
  656. opened++;
  657. continue;
  658. }
  659. if (__pattern_isCommandChar(s, i, ')'))
  660. {
  661. opened--;
  662. if (opened == 0 && firstClose == -1)
  663. firstClose = i;
  664. continue;
  665. }
  666. if (opened < 0)
  667. throw "Illegal pattern";
  668. if (__pattern_isCommandChar(s, i, '|') && opened == 0)
  669. seps.push_back(i);
  670. }
  671. if (opened != 0)
  672. throw "Illegal pattern";
  673. if (seps.size() == 0 && firstClose + 1 == (int)s.length()
  674. && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))
  675. {
  676. children.push_back(pattern(s.substr(1, s.length() - 2)));
  677. }
  678. else
  679. {
  680. if (seps.size() > 0)
  681. {
  682. seps.push_back(s.length());
  683. int last = 0;
  684. for (size_t i = 0; i < seps.size(); i++)
  685. {
  686. children.push_back(pattern(s.substr(last, seps[i] - last)));
  687. last = seps[i] + 1;
  688. }
  689. }
  690. else
  691. {
  692. size_t pos = 0;
  693. chars = __pattern_scanCharSet(s, pos);
  694. __pattern_scanCounts(s, pos, from, to);
  695. if (pos < s.length())
  696. children.push_back(pattern(s.substr(pos)));
  697. }
  698. }
  699. }
  700. /* End of pattern implementation */
  701. inline bool isEof(char c)
  702. {
  703. return (c == EOF || c == EOFC);
  704. }
  705. inline bool isEoln(char c)
  706. {
  707. return (c == LF || c == CR);
  708. }
  709. inline bool isBlanks(char c)
  710. {
  711. return (c == LF || c == CR || c == SPACE || c == TAB);
  712. }
  713. enum TMode
  714. {
  715. _input, _output, _answer
  716. };
  717. enum TResult
  718. {
  719. _ok, _wa, _pe, _fail, _dirt
  720. };
  721. const std::string outcomes[] =
  722. {"accepted", "wrong-answer", "presentation-error", "fail", "fail"};
  723. /*
  724. * Streams to be used for reading data in checkers or validators.
  725. * Each read*() method moves pointer to the next character after the
  726. * read value.
  727. */
  728. struct InStream
  729. {
  730. /* Do not use it. */
  731. InStream();
  732. std::FILE * file;
  733. std::string name;
  734. TMode mode;
  735. bool opened;
  736. bool stdfile;
  737. bool strict;
  738. void init(std::string fileName, TMode mode);
  739. void init(std::FILE* f, TMode mode);
  740. /* Moves stream pointer to the first non-white-space character or EOF. */
  741. void skipBlanks();
  742. /* Returns current character in the stream. Doesn't remove it from stream. */
  743. char curChar();
  744. /* Moves stream pointer one character forward. */
  745. void skipChar();
  746. /* Returns current character and moves pointer one character forward. */
  747. char nextChar();
  748. /* Returns current character and moves pointer one character forward. */
  749. char readChar();
  750. /* As "readChar()" but ensures that the result is equal to given parameter. */
  751. char readChar(char c);
  752. /* As "readChar()" but ensures that the result is equal to the space (code=32). */
  753. char readSpace();
  754. /* Puts back the character into the stream. */
  755. void unreadChar(char c);
  756. /* Reopens stream, you should not use it. */
  757. void reset();
  758. /* Checks that current position is EOF. If not it doesn't move stream pointer. */
  759. bool eof();
  760. /* Moves pointer to the first non-white-space character and calls "eof()". */
  761. bool seekEof();
  762. /*
  763. * Checks that current position contains EOLN.
  764. * If not it doesn't move stream pointer.
  765. * In strict mode expects "#13#10" for windows or "#10" for other platforms.
  766. */
  767. bool eoln();
  768. /* Moves pointer to the first non-space and non-tab character and calls "eoln()". */
  769. bool seekEoln();
  770. /* Moves stream pointer to the first character of the next line (if exists). */
  771. void nextLine();
  772. /*
  773. * Reads new token. Ignores white-spaces into the non-strict mode
  774. * (strict mode is used in validators usually).
  775. */
  776. std::string readWord();
  777. /* The same as "readWord()", it is preffered to use "readToken()". */
  778. std::string readToken();
  779. /* The same as "readWord()", but ensures that token matches to given pattern. */
  780. std::string readWord(const std::string& ptrn);
  781. /* The same as "readToken()", but ensures that token matches to given pattern. */
  782. std::string readToken(const std::string& ptrn);
  783. /*
  784. * Reads new long long value. Ignores white-spaces into the non-strict mode
  785. * (strict mode is used in validators usually).
  786. */
  787. long long readLong();
  788. /*
  789. * Reads new int. Ignores white-spaces into the non-strict mode
  790. * (strict mode is used in validators usually).
  791. */
  792. int readInteger();
  793. /*
  794. * Reads new int. Ignores white-spaces into the non-strict mode
  795. * (strict mode is used in validators usually).
  796. */
  797. int readInt();
  798. /* As "readLong()" but ensures that value in the range [minv,maxv]. */
  799. long long readLong(long long minv, long long maxv);
  800. /* As "readInteger()" but ensures that value in the range [minv,maxv]. */
  801. int readInteger(int minv, int maxv);
  802. /* As "readInt()" but ensures that value in the range [minv,maxv]. */
  803. int readInt(int minv, int maxv);
  804. /*
  805. * Reads new double. Ignores white-spaces into the non-strict mode
  806. * (strict mode is used in validators usually).
  807. */
  808. double readReal();
  809. /*
  810. * Reads new double. Ignores white-spaces into the non-strict mode
  811. * (strict mode is used in validators usually).
  812. */
  813. double readDouble();
  814. /* As "readReal()" but ensures that value in the range [minv,maxv]. */
  815. double readReal(double minv, double maxv);
  816. /* As "readDouble()" but ensures that value in the range [minv,maxv]. */
  817. double readDouble(double minv, double maxv);
  818. /* As readLine(). */
  819. std::string readString();
  820. /*
  821. * Reads line from the current position to EOLN or EOF. Moves stream pointer to
  822. * the first character of the new line (if possible).
  823. */
  824. std::string readLine();
  825. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  826. std::string readLine(const std::string& ptrn);
  827. /* See readLine(const std::string& ptrn). */
  828. std::string readString(const std::string& ptrn);
  829. /* Reads EOLN or fails. Use it in validators. Calls "eoln()" method internally. */
  830. void readEoln();
  831. /* Reads EOF or fails. Use it in validators. Calls "eof()" method internally. */
  832. void readEof();
  833. void quit(TResult result, const char * msg);
  834. void quits(TResult result, std::string msg);
  835. void close();
  836. const static WORD LightGray = 0x07;
  837. const static WORD LightRed = 0x0c;
  838. const static WORD LightCyan = 0x0b;
  839. const static WORD LightGreen = 0x0a;
  840. static void textColor(WORD color);
  841. static void quitscr(WORD color, const char * msg);
  842. static void quitscrS(WORD color, std::string msg);
  843. void xmlSafeWrite(std::FILE * file, const char * msg);
  844. };
  845. InStream inf;
  846. InStream ouf;
  847. InStream ans;
  848. bool appesMode;
  849. std::string resultName;
  850. std::string checkerName = "untitled checker";
  851. random rnd;
  852. /* implementation
  853. */
  854. template <typename T>
  855. static std::string vtos(const T& t)
  856. {
  857. std::string s;
  858. std::stringstream ss;
  859. ss << t;
  860. ss >> s;
  861. return s;
  862. }
  863. InStream::InStream()
  864. {
  865. file = NULL;
  866. name = "";
  867. mode = _input;
  868. strict = false;
  869. stdfile = false;
  870. }
  871. int resultExitCode(TResult r)
  872. {
  873. if (r == _ok)
  874. return OK_EXIT_CODE;
  875. if (r == _wa)
  876. return WA_EXIT_CODE;
  877. if (r == _pe)
  878. return PE_EXIT_CODE;
  879. if (r == _fail)
  880. return FAIL_EXIT_CODE;
  881. if (r == _dirt)
  882. return DIRT_EXIT_CODE;
  883. return FAIL_EXIT_CODE;
  884. }
  885. void InStream::textColor(WORD color)
  886. {
  887. #ifdef ON_WINDOWS
  888. HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
  889. SetConsoleTextAttribute(handle, color);
  890. #endif
  891. }
  892. void halt(int exitCode)
  893. {
  894. #ifdef FOOTER
  895. InStream::textColor(InStream::LightGray);
  896. std::printf("Checker: \"%s\"\n", checkerName.c_str());
  897. std::printf("Exit code: %d\n", exitCode);
  898. InStream::textColor(InStream::LightGray);
  899. #endif
  900. std::exit(exitCode);
  901. }
  902. void InStream::quit(TResult result, const char * msg)
  903. {
  904. if (mode != _output && result != _fail)
  905. quits(_fail, std::string(msg) + " (" + name + ")");
  906. std::FILE * resultFile;
  907. std::string errorName;
  908. if (result == _ok)
  909. {
  910. if (!ouf.seekEof())
  911. quit(_dirt, "Extra information in the output file");
  912. }
  913. switch (result)
  914. {
  915. case _fail:
  916. errorName = "FAIL ";
  917. quitscrS(LightRed, errorName);
  918. break;
  919. case _dirt:
  920. errorName = "wrong output format ";
  921. quitscrS(LightCyan, errorName);
  922. result = _pe;
  923. break;
  924. case _pe:
  925. errorName = "wrong output format ";
  926. quitscrS(LightRed, errorName);
  927. break;
  928. case _ok:
  929. errorName = "ok ";
  930. quitscrS(LightGreen, errorName);
  931. break;
  932. case _wa:
  933. errorName = "wrong answer ";
  934. quitscrS(LightRed, errorName);
  935. break;
  936. default:
  937. quit(_fail, "What is the code ??? ");
  938. }
  939. if (resultName != "")
  940. {
  941. resultFile = std::fopen(resultName.c_str(), "w");
  942. if (resultFile == NULL)
  943. quit(_fail, "Can not write to Result file");
  944. if (appesMode)
  945. {
  946. fprintf(resultFile, "<?xml version=\"1.0\" encoding=\"windows-1251\"?>");
  947. fprintf(resultFile, "<result outcome = \"%s\">", outcomes[(int)result].c_str());
  948. xmlSafeWrite(resultFile, msg);
  949. fprintf(resultFile, "</result>\n");
  950. }
  951. else
  952. fprintf(resultFile, "%s", msg);
  953. if (NULL == resultFile || fclose(resultFile) != 0)
  954. quit(_fail, "Can not write to Result file");
  955. }
  956. quitscr(LightGray, msg);
  957. std::printf("\n");
  958. if (inf.file)
  959. fclose(inf.file);
  960. if (ouf.file)
  961. fclose(ouf.file);
  962. if (ans.file)
  963. fclose(ans.file);
  964. textColor(LightGray);
  965. if (resultName != "")
  966. std::printf("See file to check exit message\n");
  967. halt(resultExitCode(result));
  968. }
  969. void InStream::quits(TResult result, std::string msg)
  970. {
  971. InStream::quit(result, msg.c_str());
  972. }
  973. void InStream::xmlSafeWrite(std::FILE * file, const char * msg)
  974. {
  975. size_t lmsg = strlen(msg);
  976. for (size_t i = 0; i < lmsg; i++)
  977. {
  978. if (msg[i] == '&')
  979. {
  980. fprintf(file, "%s", "&amp;");
  981. continue;
  982. }
  983. if (msg[i] == '<')
  984. {
  985. fprintf(file, "%s", "&lt;");
  986. continue;
  987. }
  988. if (msg[i] == '>')
  989. {
  990. fprintf(file, "%s", "&gt;");
  991. continue;
  992. }
  993. if (msg[i] == '"')
  994. {
  995. fprintf(file, "%s", "&quot;");
  996. continue;
  997. }
  998. if (0 <= msg[i] && msg[i] <= 31)
  999. {
  1000. fprintf(file, "%c", '.');
  1001. continue;
  1002. }
  1003. fprintf(file, "%c", msg[i]);
  1004. }
  1005. }
  1006. void InStream::quitscrS(WORD color, std::string msg)
  1007. {
  1008. quitscr(color, msg.c_str());
  1009. }
  1010. void InStream::quitscr(WORD color, const char * msg)
  1011. {
  1012. if (resultName == "")
  1013. {
  1014. textColor(color);
  1015. std::printf("%s", msg);
  1016. textColor(LightGray);
  1017. }
  1018. }
  1019. void InStream::reset()
  1020. {
  1021. if (opened && stdfile)
  1022. quit(_fail, "Can't reset standard handle");
  1023. if (opened)
  1024. close();
  1025. if (!stdfile)
  1026. if (NULL == (file = std::fopen(name.c_str(), "rb")))
  1027. {
  1028. if (mode == _output)
  1029. quits(_pe, std::string("File not found: \"") + name + "\"");
  1030. }
  1031. opened = true;
  1032. #if !defined(unix)
  1033. if (NULL != file)
  1034. {
  1035. #ifdef _MSC_VER
  1036. _setmode(_fileno(file), O_BINARY);
  1037. #else
  1038. setmode(fileno(file), O_BINARY);
  1039. #endif
  1040. }
  1041. #endif
  1042. }
  1043. void InStream::init(std::string fileName, TMode mode)
  1044. {
  1045. opened = false;
  1046. name = fileName;
  1047. stdfile = false;
  1048. this->mode = mode;
  1049. reset();
  1050. }
  1051. void InStream::init(std::FILE* f, TMode mode)
  1052. {
  1053. opened = false;
  1054. name = "untitled";
  1055. if (f == stdin)
  1056. name = "stdin", stdfile = true;
  1057. if (f == stdout)
  1058. name = "stdout", stdfile = true;
  1059. if (f == stderr)
  1060. name = "stderr", stdfile = true;
  1061. this->file = f;
  1062. this->mode = mode;
  1063. reset();
  1064. }
  1065. char InStream::curChar()
  1066. {
  1067. char c = (char)getc(file);
  1068. ungetc(c, file);
  1069. return c;
  1070. }
  1071. char InStream::nextChar()
  1072. {
  1073. return (char)getc(file);
  1074. }
  1075. char InStream::readChar()
  1076. {
  1077. return nextChar();
  1078. }
  1079. char InStream::readChar(char c)
  1080. {
  1081. char found = readChar();
  1082. if (c != found)
  1083. {
  1084. if (!isEoln(found))
  1085. quit(_pe, ("Unexpected character '" + std::string(1, found) + "', but '" + std::string(1, c) + "' expected").c_str());
  1086. else
  1087. quit(_pe, ("Unexpected character " + ("#" + vtos(int(found))) + ", but '" + std::string(1, c) + "' expected").c_str());
  1088. }
  1089. return found;
  1090. }
  1091. char InStream::readSpace()
  1092. {
  1093. return readChar(' ');
  1094. }
  1095. void InStream::unreadChar(char c)
  1096. {
  1097. ungetc(c, file);
  1098. }
  1099. void InStream::skipChar()
  1100. {
  1101. getc(file);
  1102. }
  1103. void InStream::skipBlanks()
  1104. {
  1105. char cur;
  1106. while (isBlanks(cur = readChar()));
  1107. unreadChar(cur);
  1108. }
  1109. std::string InStream::readWord()
  1110. {
  1111. if (!strict)
  1112. skipBlanks();
  1113. char cur = readChar();
  1114. if (isEof(cur))
  1115. quit(_pe, "Unexpected end of file - token expected");
  1116. if (isBlanks(cur))
  1117. quit(_pe, "Unexpected white-space - token expected");
  1118. std::string result = "";
  1119. while (!(isBlanks(cur) || cur == EOF))
  1120. {
  1121. result += cur;
  1122. cur = nextChar();
  1123. }
  1124. unreadChar(cur);
  1125. if (result.length() == 0)
  1126. quit(_pe, "Unexpected end of file or white-space - token expected");
  1127. return result;
  1128. }
  1129. std::string InStream::readToken()
  1130. {
  1131. return readWord();
  1132. }
  1133. static std::string __testlib_part(const std::string& s)
  1134. {
  1135. if (s.length() <= 64)
  1136. return s;
  1137. else
  1138. return s.substr(0, 30) + "..." + s.substr(s.length() - 31, 31);
  1139. }
  1140. std::string InStream::readWord(const std::string& ptrn)
  1141. {
  1142. pattern p(ptrn);
  1143. std::string result = readWord();
  1144. if (!p.matches(result))
  1145. quit(_pe, ("Token \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + ptrn + "\"").c_str());
  1146. return result;
  1147. }
  1148. std::string InStream::readToken(const std::string& ptrn)
  1149. {
  1150. return readWord(ptrn);
  1151. }
  1152. static bool equals(long long integer, const char* s)
  1153. {
  1154. if (integer == LLONG_MIN)
  1155. return strcmp(s, "-9223372036854775808") == 0;
  1156. if (integer == 0LL)
  1157. return strcmp(s, "0") == 0;
  1158. size_t length = strlen(s);
  1159. if (length == 0)
  1160. return false;
  1161. if (integer < 0 && s[0] != '-')
  1162. return false;
  1163. if (integer < 0)
  1164. s++, length--, integer = -integer;
  1165. if (length == 0)
  1166. return false;
  1167. while (integer > 0)
  1168. {
  1169. int digit = integer % 10;
  1170. if (s[length - 1] != '0' + digit)
  1171. return false;
  1172. length--;
  1173. integer /= 10;
  1174. }
  1175. return length == 0;
  1176. }
  1177. static double stringToDouble(InStream& in, const char* buffer)
  1178. {
  1179. double retval;
  1180. size_t length = strlen(buffer);
  1181. for (size_t i = 0; i < length; i++)
  1182. if (isBlanks(buffer[i]))
  1183. in.quit(_pe, ("Expected double, but \"" + (std::string)buffer + "\" found").c_str());
  1184. if (std::sscanf(buffer, "%lf", &retval) == 1)
  1185. return retval;
  1186. else
  1187. in.quit(_pe, ("Expected double, but \"" + (std::string)buffer + "\" found").c_str());
  1188. throw "Unexpected exception";
  1189. }
  1190. static long long stringToLongLong(InStream& in, const char* buffer)
  1191. {
  1192. if (strcmp(buffer, "-9223372036854775808") == 0)
  1193. return LLONG_MIN;
  1194. bool minus = false;
  1195. size_t length = strlen(buffer);
  1196. if (length > 1 && buffer[0] == '-')
  1197. minus = true;
  1198. if (length > 20)
  1199. in.quit(_pe, ("Expected integer, but \"" + (std::string)buffer + "\" found").c_str());
  1200. long long retval = 0LL;
  1201. int zeroes = 0;
  1202. int processingZeroes = true;
  1203. for (size_t i = (minus ? 1 : 0); i < length; i++)
  1204. {
  1205. if (buffer[i] == '0' && processingZeroes)
  1206. zeroes++;
  1207. else
  1208. processingZeroes = false;
  1209. if (buffer[i] < '0' || buffer[i] > '9')
  1210. in.quit(_pe, ("Expected integer, but \"" + (std::string)buffer + "\" found").c_str());
  1211. retval = retval * 10 + (buffer[i] - '0');
  1212. }
  1213. if (retval < 0)
  1214. in.quit(_pe, ("Expected integer, but \"" + (std::string)buffer + "\" found").c_str());
  1215. if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)
  1216. in.quit(_pe, ("Expected integer, but \"" + (std::string)buffer + "\" found").c_str());
  1217. retval = (minus ? -retval : +retval);
  1218. if (length < 19)
  1219. return retval;
  1220. if (equals(retval, buffer))
  1221. return retval;
  1222. else
  1223. in.quit(_pe, ("Expected int64, but \"" + (std::string)buffer + "\" found").c_str());
  1224. throw "Unexpected exception";
  1225. }
  1226. int InStream::readInteger()
  1227. {
  1228. if (!strict && seekEof())
  1229. quit(_pe, "Unexpected end of file - int32 expected");
  1230. std::string token = readWord();
  1231. long long value = stringToLongLong(*this, token.c_str());
  1232. if (value < INT_MIN || value > INT_MAX)
  1233. quit(_pe, ("Expected int32, but \"" + token + "\" found").c_str());
  1234. return int(value);
  1235. }
  1236. long long InStream::readLong()
  1237. {
  1238. if (!strict && seekEof())
  1239. quit(_pe, "Unexpected end of file - int64 expected");
  1240. std::string token = readWord();
  1241. return stringToLongLong(*this, token.c_str());
  1242. }
  1243. long long InStream::readLong(long long minv, long long maxv)
  1244. {
  1245. long long result = readLong();
  1246. if (result < minv || result > maxv)
  1247. quit(_pe, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1248. return result;
  1249. }
  1250. int InStream::readInt()
  1251. {
  1252. return readInteger();
  1253. }
  1254. int InStream::readInt(int minv, int maxv)
  1255. {
  1256. int result = readInt();
  1257. if (result < minv || result > maxv)
  1258. quit(_pe, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1259. return result;
  1260. }
  1261. int InStream::readInteger(int minv, int maxv)
  1262. {
  1263. return readInt(minv, maxv);
  1264. }
  1265. double InStream::readReal()
  1266. {
  1267. if (!strict && seekEof())
  1268. quit(_pe, "Unexpected end of file - double expected");
  1269. return stringToDouble(*this, readWord().c_str());
  1270. }
  1271. double InStream::readDouble()
  1272. {
  1273. return readReal();
  1274. }
  1275. double InStream::readReal(double minv, double maxv)
  1276. {
  1277. double result = readReal();
  1278. if (result < minv || result > maxv)
  1279. quit(_pe, ("Double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1280. return result;
  1281. }
  1282. double InStream::readDouble(double minv, double maxv)
  1283. {
  1284. return readReal(minv, maxv);
  1285. }
  1286. bool InStream::eof()
  1287. {
  1288. if (!strict && NULL == file)
  1289. return true;
  1290. if (feof(file) != 0)
  1291. return true;
  1292. else
  1293. {
  1294. int cur = getc(file);
  1295. if (isEof(char(cur)))
  1296. return true;
  1297. else
  1298. {
  1299. ungetc(cur, file);
  1300. return false;
  1301. }
  1302. }
  1303. }
  1304. bool InStream::seekEof()
  1305. {
  1306. if (NULL == file)
  1307. return true;
  1308. skipBlanks();
  1309. return eof();
  1310. }
  1311. bool InStream::eoln()
  1312. {
  1313. if (!strict && NULL == file)
  1314. return true;
  1315. char c = nextChar();
  1316. if (!strict)
  1317. {
  1318. if (isEof(c))
  1319. return true;
  1320. if (c == CR)
  1321. {
  1322. c = nextChar();
  1323. std::printf("%d\n", c);
  1324. if (c != LF)
  1325. {
  1326. unreadChar(CR);
  1327. unreadChar(c);
  1328. return false;
  1329. }
  1330. else
  1331. return true;
  1332. }
  1333. if (c == LF)
  1334. return true;
  1335. unreadChar(c);
  1336. return false;
  1337. }
  1338. else
  1339. {
  1340. bool returnCr = false;
  1341. #ifdef ON_WINDOWS
  1342. if (c != CR)
  1343. {
  1344. unreadChar(c);
  1345. return false;
  1346. }
  1347. else
  1348. {
  1349. if (!returnCr)
  1350. returnCr = true;
  1351. c = nextChar();
  1352. }
  1353. #endif
  1354. if (c != LF)
  1355. {
  1356. if (returnCr)
  1357. unreadChar(CR);
  1358. unreadChar(LF);
  1359. return false;
  1360. }
  1361. return true;
  1362. }
  1363. }
  1364. void InStream::readEoln()
  1365. {
  1366. if (!eoln())
  1367. quit(_pe, "Expected EOLN");
  1368. }
  1369. void InStream::readEof()
  1370. {
  1371. if (!eof())
  1372. quit(_pe, "Expected EOF");
  1373. }
  1374. bool InStream::seekEoln()
  1375. {
  1376. if (NULL == file)
  1377. return true;
  1378. char cur;
  1379. do
  1380. {
  1381. cur = nextChar();
  1382. }
  1383. while (cur == SPACE || cur == TAB);
  1384. ungetc(cur, file);
  1385. return eoln();
  1386. }
  1387. void InStream::nextLine()
  1388. {
  1389. if (NULL == file)
  1390. return;
  1391. char cur;
  1392. while (!isEoln(cur = readChar()));
  1393. if (cur == CR)
  1394. {
  1395. cur = readChar();
  1396. if (cur != LF)
  1397. unreadChar(cur);
  1398. }
  1399. else
  1400. {
  1401. if (cur != LF)
  1402. unreadChar(cur);
  1403. }
  1404. }
  1405. std::string InStream::readString()
  1406. {
  1407. if (NULL == file)
  1408. quit(_pe, "Expected line");
  1409. std::string retval = "";
  1410. char cur;
  1411. for (;;)
  1412. {
  1413. cur = readChar();
  1414. if (isEoln(cur))
  1415. break;
  1416. if (isEof(cur))
  1417. break;
  1418. retval += cur;
  1419. }
  1420. unreadChar(cur);
  1421. if (strict)
  1422. readEoln();
  1423. else
  1424. eoln();
  1425. return retval;
  1426. }
  1427. std::string InStream::readString(const std::string& ptrn)
  1428. {
  1429. pattern p(ptrn);
  1430. std::string result = readString();
  1431. if (!p.matches(result))
  1432. quit(_pe, ("Line \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + ptrn + "\"").c_str());
  1433. return result;
  1434. }
  1435. std::string InStream::readLine()
  1436. {
  1437. return readString();
  1438. }
  1439. std::string InStream::readLine(const std::string& ptrn)
  1440. {
  1441. return readString(ptrn);
  1442. }
  1443. void InStream::close()
  1444. {
  1445. if (opened)
  1446. fclose(file);
  1447. opened = false;
  1448. }
  1449. void quit(TResult result, const std::string& msg)
  1450. {
  1451. ouf.quit(result, msg.c_str());
  1452. }
  1453. void quit(TResult result, const char * msg)
  1454. {
  1455. ouf.quit(result, msg);
  1456. }
  1457. void quitf(TResult result, const char * format, ...)
  1458. {
  1459. char * buffer = new char [MAX_FORMAT_BUFFER_SIZE];
  1460. va_list ap;
  1461. va_start(ap, format);
  1462. std::vsprintf(buffer, format, ap);
  1463. va_end(ap);
  1464. std::string output(buffer);
  1465. delete[] buffer;
  1466. quit(result, output);
  1467. }
  1468. void registerGen(int argc, char* argv[])
  1469. {
  1470. rnd.setSeed(argc, argv);
  1471. }
  1472. void registerValidation()
  1473. {
  1474. inf.init(stdin, _input);
  1475. inf.strict = true;
  1476. }
  1477. void registerTestlibCmd(int argc, char * argv[])
  1478. {
  1479. if (argc > 1 && !strcmp("--help", argv[1]))
  1480. {
  1481. InStream::textColor(InStream::LightCyan);
  1482. std::printf("TESTLIB %s ", VERSION);
  1483. std::printf("by Mike Mirzayanov, copyright(c) 2005-2009\n");
  1484. std::printf("Checker name: \"%s\"\n", checkerName.c_str());
  1485. InStream::textColor(InStream::LightGray);
  1486. std::printf("\n");
  1487. std::printf("Latest features: \n");
  1488. for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char*); i++)
  1489. {
  1490. std::printf("*) %s\n", latestFeatures[i]);
  1491. }
  1492. std::printf("\n");
  1493. std::printf("Program must be run with the following arguments: \n");
  1494. std::printf(" <input-file> <output-file> <answer-file> [<report-file> [<-appes>]]\n\n");
  1495. std::exit(0);
  1496. }
  1497. // testlib assumes: sizeof(int) = 4.
  1498. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  1499. // testlib assumes: sizeof(long long) = 8.
  1500. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  1501. if (argc < 4 || argc > 6)
  1502. {
  1503. quit(_fail, std::string("Program must be run with the following arguments: ") +
  1504. std::string("<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]") +
  1505. "\nUse \"--help\" to get help information");
  1506. }
  1507. if (argc == 4)
  1508. {
  1509. resultName = "";
  1510. appesMode = false;
  1511. }
  1512. if (argc == 5)
  1513. {
  1514. resultName = argv[4];
  1515. appesMode = false;
  1516. }
  1517. if (argc == 6)
  1518. {
  1519. if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5]))
  1520. {
  1521. quit(_fail, std::string("Program must be run with the following arguments: ") +
  1522. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  1523. }
  1524. else
  1525. {
  1526. resultName = argv[4];
  1527. appesMode = true;
  1528. }
  1529. }
  1530. inf.init(argv[1], _input);
  1531. ouf.init(argv[2], _output);
  1532. ans.init(argv[3], _answer);
  1533. }
  1534. void registerTestlib(int argc, ...)
  1535. {
  1536. if (argc < 3 || argc > 5)
  1537. quit(_fail, std::string("Program must be run with the following arguments: ") +
  1538. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  1539. char ** argv = new char*[argc + 1];
  1540. va_list ap;
  1541. va_start(ap, argc);
  1542. argv[0] = NULL;
  1543. for (int i = 0; i < argc; i++)
  1544. {
  1545. argv[i + 1] = va_arg(ap, char *);
  1546. }
  1547. va_end(ap);
  1548. registerTestlibCmd(argc + 1, argv);
  1549. delete[] argv;
  1550. }
  1551. inline bool isNaN(double r)
  1552. {
  1553. return ((r != r) == true) && ((r == r) == false) && ((1.0 > r) == false) && ((1.0 < r) == false);
  1554. }
  1555. inline bool isInfinite(double r)
  1556. {
  1557. return (r > 1E100 || r < -1E100);
  1558. }
  1559. bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)
  1560. {
  1561. if(isNaN(expected))
  1562. {
  1563. return isNaN(result);
  1564. }
  1565. else
  1566. if(isInfinite(expected))
  1567. {
  1568. if(expected > 0)
  1569. {
  1570. return result > 0 && isInfinite(result);
  1571. }
  1572. else
  1573. {
  1574. return result < 0 && isInfinite(result);
  1575. }
  1576. }
  1577. else
  1578. if(isNaN(result) || isInfinite(result))
  1579. {
  1580. return false;
  1581. }
  1582. else
  1583. if(__testlib_abs(result - expected) < MAX_DOUBLE_ERROR)
  1584. {
  1585. return true;
  1586. }
  1587. else
  1588. {
  1589. double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),
  1590. expected * (1.0 + MAX_DOUBLE_ERROR));
  1591. double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),
  1592. expected * (1.0 + MAX_DOUBLE_ERROR));
  1593. return result > minv && result < maxv;
  1594. }
  1595. }
  1596. double doubleDelta(double expected, double result)
  1597. {
  1598. double absolute = __testlib_abs(result - expected);
  1599. if (__testlib_abs(expected) > 1E-9)
  1600. {
  1601. double relative = __testlib_abs(absolute / expected);
  1602. return __testlib_min(absolute, relative);
  1603. }
  1604. else
  1605. return absolute;
  1606. }
  1607. static void __testlib_ensure(bool cond, const std::string msg)
  1608. {
  1609. if (!cond)
  1610. quitf(_fail, msg.c_str());
  1611. }
  1612. #define ensure(cond) __testlib_ensure(cond, std::string("Condition failed: \"") + #cond + "\"")
  1613. void ensuref(bool cond, const char* format, ...)
  1614. {
  1615. char * buffer = new char [MAX_FORMAT_BUFFER_SIZE];
  1616. va_list ap;
  1617. va_start(ap, format);
  1618. std::vsprintf(buffer, format, ap);
  1619. va_end(ap);
  1620. std::string message(buffer);
  1621. delete[] buffer;
  1622. __testlib_ensure(cond, message);
  1623. }
  1624. void setName(const char* format, ...)
  1625. {
  1626. char * buffer = new char [MAX_FORMAT_BUFFER_SIZE];
  1627. va_list ap;
  1628. va_start(ap, format);
  1629. std::vsprintf(buffer, format, ap);
  1630. va_end(ap);
  1631. std::string name(buffer);
  1632. delete[] buffer;
  1633. checkerName = name;
  1634. }
  1635. #endif