Advertisement
Guest User

Testlib.h to Contestrer

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