1
0

testlib.h 48 KB

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