#include <iostream> #include <set> #include <map> #include <limits> #include <vector> #include <iomanip> // for std::setw #include <ios> // for std::noskipws, streamsize #include <istream> // for std::istream #include <ostream> // for std::ostream #include <sstream> // for std::ostringstream #include <cstddef> // for NULL #include <stdexcept> // for std::domain_error #include <string> // for std::string implicit constructor #include <cstdlib> // for std::abs #include <limits> // for std::numeric_limits #include<type_traits> using namespace std; # define throw(x) throw(x) namespace boost { template<bool B, class T = void> struct enable_if_c { typedef T type; }; template<class T> struct enable_if_c<false, T> { }; template<bool B, class T = void> struct disable_if_c { typedef T type; }; template<class T> struct disable_if_c<true, T> { }; }; #include <cassert> #include <climits> #include <iterator> #include <algorithm> #include <limits> #include <type_traits> namespace boost { template <class I> class rational; namespace integer { namespace gcd_detail{ template <class T> inline constexpr T constexpr_min(T const& a, T const& b) noexcept { return a < b ? a : b; } template <class T> inline constexpr auto constexpr_swap(T&a, T& b) noexcept -> decltype(a.swap(b)) { return a.swap(b); } template <class T, class U> inline constexpr void constexpr_swap(T&a, U& b...) noexcept { T t(static_cast<T&&>(a)); a = static_cast<T&&>(b); b = static_cast<T&&>(t); } template <class T, bool a = std::is_unsigned<T>::value || (std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_signed)> struct gcd_traits_abs_defaults { inline static constexpr const T& abs(const T& val) noexcept { return val; } }; template <class T> struct gcd_traits_abs_defaults<T, false> { inline static T constexpr abs(const T& val) noexcept { // This sucks, but std::abs is not constexpr :( return val < T(0) ? -val : val; } }; enum method_type { method_euclid = 0, method_binary = 1, method_mixed = 2 }; struct any_convert { template <class T> any_convert(const T&); }; struct unlikely_size { char buf[9973]; }; unlikely_size operator <<= (any_convert, any_convert); unlikely_size operator >>= (any_convert, any_convert); template <class T> struct gcd_traits_defaults : public gcd_traits_abs_defaults<T> { inline static constexpr unsigned make_odd(T& val) noexcept { unsigned r = 0; while(0 == (val & 1u)) { val >>= 1; ++r; } return r; } inline static constexpr bool less(const T& a, const T& b) noexcept { return a < b; } static T& get_value(); static const bool has_operator_left_shift_equal = sizeof(get_value() <<= 2) != sizeof(unlikely_size); static const bool has_operator_right_shift_equal = sizeof(get_value() >>= 2) != sizeof(unlikely_size); static const method_type method = std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && has_operator_left_shift_equal && has_operator_right_shift_equal ? method_mixed : method_euclid; }; // // Default gcd_traits just inherits from defaults: // template <class T> struct gcd_traits : public gcd_traits_defaults<T> {}; // // The Mixed Binary Euclid Algorithm // Sidi Mohamed Sedjelmaci // Electronic Notes in Discrete Mathematics 35 (2009) 169-176 // template <class T> constexpr T mixed_binary_gcd(T u, T v) noexcept { if(gcd_traits<T>::less(u, v)) constexpr_swap(u, v); unsigned shifts = 0; if(u == T(0)) return v; if(v == T(0)) return u; shifts = constexpr_min(gcd_traits<T>::make_odd(u), gcd_traits<T>::make_odd(v)); while(gcd_traits<T>::less(1, v)) { u %= v; v -= u; if(u == T(0)) return v << shifts; if(v == T(0)) return u << shifts; gcd_traits<T>::make_odd(u); gcd_traits<T>::make_odd(v); if(gcd_traits<T>::less(u, v)) constexpr_swap(u, v); } return (v == 1 ? v : u) << shifts; } /** Stein gcd (aka 'binary gcd') * * From Mathematics to Generic Programming, Alexander Stepanov, Daniel Rose */ template <typename SteinDomain> constexpr SteinDomain Stein_gcd(SteinDomain m, SteinDomain n) noexcept { assert(m >= 0); assert(n >= 0); if (m == SteinDomain(0)) return n; if (n == SteinDomain(0)) return m; // m > 0 && n > 0 unsigned d_m = gcd_traits<SteinDomain>::make_odd(m); unsigned d_n = gcd_traits<SteinDomain>::make_odd(n); // odd(m) && odd(n) while (m != n) { if (n > m) constexpr_swap(n, m); m -= n; gcd_traits<SteinDomain>::make_odd(m); } // m == n m <<= constexpr_min(d_m, d_n); return m; } /** Euclidean algorithm * * From Mathematics to Generic Programming, Alexander Stepanov, Daniel Rose * */ template <typename EuclideanDomain> inline constexpr EuclideanDomain Euclid_gcd(EuclideanDomain a, EuclideanDomain b) noexcept { while (b != EuclideanDomain(0)) { a %= b; constexpr_swap(a, b); } return a; } template <typename T> inline constexpr typename enable_if_c<gcd_traits<T>::method == method_mixed, T>::type optimal_gcd_select(T const &a, T const &b) noexcept { return gcd_detail::mixed_binary_gcd(a, b); } template <typename T> inline constexpr typename enable_if_c<gcd_traits<T>::method == method_binary, T>::type optimal_gcd_select(T const &a, T const &b) noexcept { return gcd_detail::Stein_gcd(a, b); } template <typename T> inline constexpr typename enable_if_c<gcd_traits<T>::method == method_euclid, T>::type optimal_gcd_select(T const &a, T const &b) noexcept { return gcd_detail::Euclid_gcd(a, b); } template <class T> inline constexpr T lcm_imp(const T& a, const T& b) noexcept { T temp = boost::integer::gcd_detail::optimal_gcd_select(a, b); return (temp != T(0)) ? T(a / temp * b) : T(0); } } // namespace detail template <typename Integer> inline constexpr Integer gcd(Integer const &a, Integer const &b) noexcept { if(a == (std::numeric_limits<Integer>::min)()) return a == static_cast<Integer>(0) ? gcd_detail::gcd_traits<Integer>::abs(b) : boost::integer::gcd(static_cast<Integer>(a % b), b); else if (b == (std::numeric_limits<Integer>::min)()) return b == static_cast<Integer>(0) ? gcd_detail::gcd_traits<Integer>::abs(a) : boost::integer::gcd(a, static_cast<Integer>(b % a)); return gcd_detail::optimal_gcd_select(static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(a)), static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(b))); } template <typename Integer> inline constexpr Integer lcm(Integer const &a, Integer const &b) noexcept { return gcd_detail::lcm_imp(static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(a)), static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(b))); } } // namespace integer } // namespace boost namespace boost { namespace rational_detail{ template <class FromInt, class ToInt> struct is_compatible_integer { static const bool value = ((std::numeric_limits<FromInt>::is_specialized && std::numeric_limits<FromInt>::is_integer && (std::numeric_limits<FromInt>::digits <= std::numeric_limits<ToInt>::digits) && (std::numeric_limits<FromInt>::radix == std::numeric_limits<ToInt>::radix) && ((std::numeric_limits<FromInt>::is_signed == false) || (std::numeric_limits<ToInt>::is_signed == true)) && is_convertible<FromInt, ToInt>::value) || is_same<FromInt, ToInt>::value) || (is_class<ToInt>::value && is_class<FromInt>::value && is_convertible<FromInt, ToInt>::value); }; } class bad_rational : public std::domain_error { public: explicit bad_rational() : std::domain_error("bad rational: zero denominator") {} explicit bad_rational( char const *what ) : std::domain_error( what ) {} }; template <typename IntType> class rational { // Class-wide pre-conditions static_assert( ::std::numeric_limits<IntType>::is_specialized ); // Helper types using param_type = IntType; struct helper { IntType parts[2]; }; typedef IntType (helper::* bool_type)[2]; public: // Component type typedef IntType int_type; constexpr rational() : num(0), den(1) {} template <class T> constexpr rational(const T& n) : num(n), den(1) {} template <class T, class U> constexpr rational(const T& n, const U& d) : num(n), den(d) { normalize(); } template < typename NewType > constexpr explicit rational(rational<NewType> const &r, typename enable_if_c<rational_detail::is_compatible_integer<NewType, IntType>::value>::type const* = 0) : num(r.numerator()), den(is_normalized(int_type(r.numerator()), int_type(r.denominator())) ? r.denominator() : (throw(bad_rational("bad rational: denormalized conversion")), 0)){} template < typename NewType > constexpr explicit rational(rational<NewType> const &r, typename disable_if_c<rational_detail::is_compatible_integer<NewType, IntType>::value>::type const* = 0) : num(r.numerator()), den(is_normalized(int_type(r.numerator()), int_type(r.denominator())) && is_safe_narrowing_conversion(r.denominator()) && is_safe_narrowing_conversion(r.numerator()) ? r.denominator() : (throw(bad_rational("bad rational: denormalized conversion")), 0)){} // Default copy constructor and assignment are fine // Add assignment from IntType template <class T> constexpr typename enable_if_c< rational_detail::is_compatible_integer<T, IntType>::value, rational & >::type operator=(const T& n) { return assign(static_cast<IntType>(n), static_cast<IntType>(1)); } // Assign in place template <class T, class U> constexpr typename enable_if_c< rational_detail::is_compatible_integer<T, IntType>::value && rational_detail::is_compatible_integer<U, IntType>::value, rational & >::type assign(const T& n, const U& d) { return *this = rational<IntType>(static_cast<IntType>(n), static_cast<IntType>(d)); } // // The following overloads should probably *not* be provided - // but are provided for backwards compatibity reasons only. // These allow for construction/assignment from types that // are wider than IntType only if there is an implicit // conversion from T to IntType, they will throw a bad_rational // if the conversion results in loss of precision or undefined behaviour. // template <class T> constexpr rational(const T& n, typename enable_if_c< std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && !rational_detail::is_compatible_integer<T, IntType>::value && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) && is_convertible<T, IntType>::value >::type const* = 0) { assign(n, static_cast<T>(1)); } template <class T, class U> constexpr rational(const T& n, const U& d, typename enable_if_c< (!rational_detail::is_compatible_integer<T, IntType>::value || !rational_detail::is_compatible_integer<U, IntType>::value) && std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) && is_convertible<T, IntType>::value && std::numeric_limits<U>::is_specialized && std::numeric_limits<U>::is_integer && (std::numeric_limits<U>::radix == std::numeric_limits<IntType>::radix) && is_convertible<U, IntType>::value >::type const* = 0) { assign(n, d); } template <class T> constexpr typename enable_if_c< std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && !rational_detail::is_compatible_integer<T, IntType>::value && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) && is_convertible<T, IntType>::value, rational & >::type operator=(const T& n) { return assign(n, static_cast<T>(1)); } template <class T, class U> constexpr typename enable_if_c< (!rational_detail::is_compatible_integer<T, IntType>::value || !rational_detail::is_compatible_integer<U, IntType>::value) && std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) && is_convertible<T, IntType>::value && std::numeric_limits<U>::is_specialized && std::numeric_limits<U>::is_integer && (std::numeric_limits<U>::radix == std::numeric_limits<IntType>::radix) && is_convertible<U, IntType>::value, rational & >::type assign(const T& n, const U& d) { if(!is_safe_narrowing_conversion(n) || !is_safe_narrowing_conversion(d)) throw(bad_rational()); return *this = rational<IntType>(static_cast<IntType>(n), static_cast<IntType>(d)); } // Access to representation constexpr const IntType& numerator() const { return num; } constexpr const IntType& denominator() const { return den; } // Arithmetic assignment operators constexpr rational& operator+= (const rational& r); constexpr rational& operator-= (const rational& r); constexpr rational& operator*= (const rational& r); constexpr rational& operator/= (const rational& r); template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator+= (const T& i) { num += i * den; return *this; } template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator-= (const T& i) { num -= i * den; return *this; } template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator*= (const T& i) { // Avoid overflow and preserve normalization IntType gcd = integer::gcd(static_cast<IntType>(i), den); num *= i / gcd; den /= gcd; return *this; } template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator/= (const T& i) { // Avoid repeated construction IntType const zero(0); if(i == zero) throw(bad_rational()); if(num == zero) return *this; // Avoid overflow and preserve normalization IntType const gcd = integer::gcd(num, static_cast<IntType>(i)); num /= gcd; den *= i / gcd; if(den < zero) { num = -num; den = -den; } return *this; } // Increment and decrement constexpr const rational& operator++() { num += den; return *this; } constexpr const rational& operator--() { num -= den; return *this; } constexpr rational operator++(int) { rational t(*this); ++(*this); return t; } constexpr rational operator--(int) { rational t(*this); --(*this); return t; } // Operator not constexpr bool operator!() const { return !num; } // Boolean conversion constexpr operator bool_type() const { return operator !() ? 0 : &helper::parts; } // Comparison operators constexpr bool operator< (const rational& r) const; constexpr bool operator> (const rational& r) const { return r < *this; } constexpr bool operator== (const rational& r) const; template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator< (const T& i) const { // Avoid repeated construction int_type const zero(0); // Break value into mixed-fraction form, w/ always-nonnegative remainder assert(this->den > zero); int_type q = this->num / this->den, r = this->num % this->den; while(r < zero) { r += this->den; --q; } // Compare with just the quotient, since the remainder always bumps the // value up. [Since q = floor(n/d), and if n/d < i then q < i, if n/d == i // then q == i, if n/d == i + r/d then q == i, and if n/d >= i + 1 then // q >= i + 1 > i; therefore n/d < i iff q < i.] return q < i; } template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator>(const T& i) const { return operator==(i) ? false : !operator<(i); } template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator== (const T& i) const { return ((den == IntType(1)) && (num == i)); } private: // Implementation - numerator and denominator (normalized). // Other possibilities - separate whole-part, or sign, fields? IntType num; IntType den; // Helper functions static constexpr int_type inner_gcd( param_type a, param_type b, int_type const &zero = int_type(0) ) { return b == zero ? a : inner_gcd(b, a % b, zero); } static constexpr int_type inner_abs( param_type x, int_type const &zero = int_type(0) ) { return x < zero ? -x : +x; } // Representation note: Fractions are kept in normalized form at all // times. normalized form is defined as gcd(num,den) == 1 and den > 0. // In particular, note that the implementation of abs() below relies // on den always being positive. constexpr bool test_invariant() const; constexpr void normalize(); static constexpr bool is_normalized( param_type n, param_type d, int_type const &zero = int_type(0), int_type const &one = int_type(1) ) { return d > zero && ( n != zero || d == one ) && inner_abs( inner_gcd(n, d, zero), zero ) == one; } // // Conversion checks: // // (1) From an unsigned type with more digits than IntType: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val) { return val < (T(1) << std::numeric_limits<IntType>::digits); } // // (2) From a signed type with more digits than IntType, and IntType also signed: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T& val) { // Note that this check assumes IntType has a 2's complement representation, // we don't want to try to convert a std::numeric_limits<IntType>::min() to // a T because that conversion may not be allowed (this happens when IntType // is from Boost.Multiprecision). return (val < (T(1) << std::numeric_limits<IntType>::digits)) && (val >= -(T(1) << std::numeric_limits<IntType>::digits)); } // // (3) From a signed type with more digits than IntType, and IntType unsigned: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val) { return (val < (T(1) << std::numeric_limits<IntType>::digits)) && (val >= 0); } // // (4) From a signed type with fewer digits than IntType, and IntType unsigned: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val) { return val >= 0; } // // (5) From an unsigned type with fewer digits than IntType, and IntType signed: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T&) { return true; } // // (6) From an unsigned type with fewer digits than IntType, and IntType unsigned: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T&) { return true; } // // (7) From an signed type with fewer digits than IntType, and IntType signed: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T&) { return true; } }; // Unary plus and minus template <typename IntType> constexpr inline rational<IntType> operator+ (const rational<IntType>& r) { return r; } template <typename IntType> constexpr inline rational<IntType> operator- (const rational<IntType>& r) { return rational<IntType>(static_cast<IntType>(-r.numerator()), r.denominator()); } // Arithmetic assignment operators template <typename IntType> constexpr rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r) { // This calculation avoids overflow, and minimises the number of expensive // calculations. Thanks to Nickolay Mladenov for this algorithm. // // Proof: // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1. // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1 // // The result is (a*d1 + c*b1) / (b1*d1*g). // Now we have to normalize this ratio. // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1 // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a. // But since gcd(a,b1)=1 we have h=1. // Similarly h|d1 leads to h=1. // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g) // Which proves that instead of normalizing the result, it is better to // divide num and den by gcd((a*d1 + c*b1), g) // Protect against self-modification IntType r_num = r.num; IntType r_den = r.den; IntType g = integer::gcd(den, r_den); den /= g; // = b1 from the calculations above num = num * (r_den / g) + r_num * den; g = integer::gcd(num, g); num /= g; den *= r_den/g; return *this; } template <typename IntType> constexpr rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r) { // Protect against self-modification IntType r_num = r.num; IntType r_den = r.den; // This calculation avoids overflow, and minimises the number of expensive // calculations. It corresponds exactly to the += case above IntType g = integer::gcd(den, r_den); den /= g; num = num * (r_den / g) - r_num * den; g = integer::gcd(num, g); num /= g; den *= r_den/g; return *this; } template <typename IntType> constexpr rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r) { // Protect against self-modification IntType r_num = r.num; IntType r_den = r.den; // Avoid overflow and preserve normalization IntType gcd1 = integer::gcd(num, r_den); IntType gcd2 = integer::gcd(r_num, den); num = (num/gcd1) * (r_num/gcd2); den = (den/gcd2) * (r_den/gcd1); return *this; } template <typename IntType> constexpr rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r) { // Protect against self-modification IntType r_num = r.num; IntType r_den = r.den; // Avoid repeated construction IntType zero(0); // Trap division by zero if (r_num == zero) throw(bad_rational()); if (num == zero) return *this; // Avoid overflow and preserve normalization IntType gcd1 = integer::gcd(num, r_num); IntType gcd2 = integer::gcd(r_den, den); num = (num/gcd1) * (r_den/gcd2); den = (den/gcd2) * (r_num/gcd1); if (den < zero) { num = -num; den = -den; } return *this; } // // Non-member operators: previously these were provided by Boost.Operator, but these had a number of // drawbacks, most notably, that in order to allow inter-operability with IntType code such as this: // // rational<int> r(3); // assert(r == 3.5); // compiles and passes!! // // Happens to be allowed as well :-( // // There are three possible cases for each operator: // 1) rational op rational. // 2) rational op integer // 3) integer op rational // Cases (1) and (2) are folded into the one function. // template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type operator + (const rational<IntType>& a, const Arg& b) { rational<IntType> t(a); return t += b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type operator + (const Arg& b, const rational<IntType>& a) { rational<IntType> t(a); return t += b; } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type operator - (const rational<IntType>& a, const Arg& b) { rational<IntType> t(a); return t -= b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type operator - (const Arg& b, const rational<IntType>& a) { rational<IntType> t(a); return -(t -= b); } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type operator * (const rational<IntType>& a, const Arg& b) { rational<IntType> t(a); return t *= b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type operator * (const Arg& b, const rational<IntType>& a) { rational<IntType> t(a); return t *= b; } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type operator / (const rational<IntType>& a, const Arg& b) { rational<IntType> t(a); return t /= b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type operator / (const Arg& b, const rational<IntType>& a) { rational<IntType> t(b); return t /= a; } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type operator <= (const rational<IntType>& a, const Arg& b) { return !(a > b); } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator <= (const Arg& b, const rational<IntType>& a) { return a >= b; } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type operator >= (const rational<IntType>& a, const Arg& b) { return !(a < b); } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator >= (const Arg& b, const rational<IntType>& a) { return a <= b; } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type operator != (const rational<IntType>& a, const Arg& b) { return !(a == b); } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator != (const Arg& b, const rational<IntType>& a) { return !(b == a); } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator < (const Arg& b, const rational<IntType>& a) { return a > b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator > (const Arg& b, const rational<IntType>& a) { return a < b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator == (const Arg& b, const rational<IntType>& a) { return a == b; } // Comparison operators template <typename IntType> constexpr bool rational<IntType>::operator< (const rational<IntType>& r) const { // Avoid repeated construction int_type const zero( 0 ); // This should really be a class-wide invariant. The reason for these // checks is that for 2's complement systems, INT_MIN has no corresponding // positive, so negating it during normalization keeps it INT_MIN, which // is bad for later calculations that assume a positive denominator. assert( this->den > zero ); assert( r.den > zero ); // Determine relative order by expanding each value to its simple continued // fraction representation using the Euclidian GCD algorithm. struct { int_type n, d, q, r; } ts = { this->num, this->den, static_cast<int_type>(this->num / this->den), static_cast<int_type>(this->num % this->den) }, rs = { r.num, r.den, static_cast<int_type>(r.num / r.den), static_cast<int_type>(r.num % r.den) }; unsigned reverse = 0u; // Normalize negative moduli by repeatedly adding the (positive) denominator // and decrementing the quotient. Later cycles should have all positive // values, so this only has to be done for the first cycle. (The rules of // C++ require a nonnegative quotient & remainder for a nonnegative dividend // & positive divisor.) while ( ts.r < zero ) { ts.r += ts.d; --ts.q; } while ( rs.r < zero ) { rs.r += rs.d; --rs.q; } // Loop through and compare each variable's continued-fraction components for ( ;; ) { // The quotients of the current cycle are the continued-fraction // components. Comparing two c.f. is comparing their sequences, // stopping at the first difference. if ( ts.q != rs.q ) { // Since reciprocation changes the relative order of two variables, // and c.f. use reciprocals, the less/greater-than test reverses // after each index. (Start w/ non-reversed @ whole-number place.) return reverse ? ts.q > rs.q : ts.q < rs.q; } // Prepare the next cycle reverse ^= 1u; if ( (ts.r == zero) || (rs.r == zero) ) { // At least one variable's c.f. expansion has ended break; } ts.n = ts.d; ts.d = ts.r; ts.q = ts.n / ts.d; ts.r = ts.n % ts.d; rs.n = rs.d; rs.d = rs.r; rs.q = rs.n / rs.d; rs.r = rs.n % rs.d; } // Compare infinity-valued components for otherwise equal sequences if ( ts.r == rs.r ) { // Both remainders are zero, so the next (and subsequent) c.f. // components for both sequences are infinity. Therefore, the sequences // and their corresponding values are equal. return false; } else { #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable:4800) #endif // Exactly one of the remainders is zero, so all following c.f. // components of that variable are infinity, while the other variable // has a finite next c.f. component. So that other variable has the // lesser value (modulo the reversal flag!). return ( ts.r != zero ) != static_cast<bool>( reverse ); #ifdef BOOST_MSVC #pragma warning(pop) #endif } } template <typename IntType> constexpr inline bool rational<IntType>::operator== (const rational<IntType>& r) const { return ((num == r.num) && (den == r.den)); } // Invariant check template <typename IntType> constexpr inline bool rational<IntType>::test_invariant() const { return ( this->den > int_type(0) ) && ( integer::gcd(this->num, this->den) == int_type(1) ); } // Normalisation template <typename IntType> constexpr void rational<IntType>::normalize() { // Avoid repeated construction IntType zero(0); if (den == zero) throw(bad_rational()); // Handle the case of zero separately, to avoid division by zero if (num == zero) { den = IntType(1); return; } IntType g = integer::gcd(num, den); num /= g; den /= g; if (den < -(std::numeric_limits<IntType>::max)()) { throw(bad_rational("bad rational: non-zero singular denominator")); } // Ensure that the denominator is positive if (den < zero) { num = -num; den = -den; } assert( this->test_invariant() ); } #ifndef BOOST_NO_IOSTREAM namespace detail { // A utility class to reset the format flags for an istream at end // of scope, even in case of exceptions struct resetter { resetter(std::istream& is) : is_(is), f_(is.flags()) {} ~resetter() { is_.flags(f_); } std::istream& is_; std::istream::fmtflags f_; // old GNU c++ lib has no ios_base }; } // Input and output template <typename IntType> std::istream& operator>> (std::istream& is, rational<IntType>& r) { using std::ios; IntType n = IntType(0), d = IntType(1); char c = 0; detail::resetter sentry(is); if ( is >> n ) { if ( is.get(c) ) { if ( c == '/' ) { if ( is >> std::noskipws >> d ) try { r.assign( n, d ); } catch ( bad_rational & ) { // normalization fail try { is.setstate(ios::failbit); } catch ( ... ) {} // don't throw ios_base::failure... if ( is.exceptions() & ios::failbit ) throw; // ...but the original exception instead // ELSE: suppress the exception, use just error flags } } else is.setstate( ios::failbit ); } } return is; } // Add manipulators for output format? template <typename IntType> std::ostream& operator<< (std::ostream& os, const rational<IntType>& r) { // The slash directly precedes the denominator, which has no prefixes. std::ostringstream ss; ss.copyfmt( os ); ss.tie( NULL ); ss.exceptions( std::ios::goodbit ); ss.width( 0 ); ss << std::noshowpos << std::noshowbase << '/' << r.denominator(); // The numerator holds the showpos, internal, and showbase flags. std::string const tail = ss.str(); std::streamsize const w = os.width() - static_cast<std::streamsize>( tail.size() ); ss.clear(); ss.str( "" ); ss.flags( os.flags() ); ss << std::setw( w < 0 || (os.flags() & std::ios::adjustfield) != std::ios::internal ? 0 : w ) << r.numerator(); return os << ss.str() + tail; } #endif // BOOST_NO_IOSTREAM // Type conversion template <typename T, typename IntType> constexpr inline T rational_cast(const rational<IntType>& src) { return static_cast<T>(src.numerator())/static_cast<T>(src.denominator()); } // Do not use any abs() defined on IntType - it isn't worth it, given the // difficulties involved (Koenig lookup required, there may not *be* an abs() // defined, etc etc). template <typename IntType> constexpr inline rational<IntType> abs(const rational<IntType>& r) { return r.numerator() >= IntType(0)? r: -r; } } // namespace boost using rational = boost::rational<unsigned long long>; struct Teacup { unsigned long long temperature; rational volume; Teacup(int temperature, rational volume) : temperature(temperature), volume(volume) {} bool operator==(const Teacup& second) const noexcept { return this->temperature == second.temperature; } bool operator<(const Teacup& second) const noexcept { return this->temperature < second.temperature; } }; ostream& operator<<(ostream& os, const Teacup& teacup) { os << "(t: " << teacup.temperature << ", v: " << teacup.volume << ")"; return os; } //ostream& operator<<(ostream& os, const pair<int,int>& teacup) //{ // os << "(t: " << teacup.first << ", v: " << teacup.second << ")"; // return os; //} ostream& operator<<(ostream& os, const pair<rational, rational>& teacup) { os << "(t: " << teacup.first << ", v: " << teacup.second << ")"; return os; } //#define DEBUG #ifdef DEBUG #define dbg cerr #else #define dbg 0 && cerr #endif template<typename T> void clear_with_zeros(T& mapa) { std::vector<rational> keys_to_remove; for(const auto& [key, value]: mapa) { if (value == 0ull) { keys_to_remove.push_back(key); } } for (const auto& key: keys_to_remove) { mapa.erase(key); } } bool solve() { int n; cin >> n; map<rational, rational> all_start, all_end; for (int i = 0; i < n; ++i) { int l, start, end; cin >> l >> start >> end; if (all_start.count(1ull * start) == 0) { all_start[1ull * start] = 0; } if (all_end.count(1ull* end) == 0) { all_end[1ull* end] = 0; } all_start[1ull* start] += 1ull* l; all_end[1ull* end] += 1ull* l; } #ifdef DEBUG dbg << "Start: "; for(const auto& x: all_start) { dbg << x << " "; } dbg << endl << endl << "End: "; for(const auto& x: all_end) { dbg << x << " "; } dbg << endl << endl; #endif // satisfy correct cups for(auto& [temp, volume]: all_end) { if (all_start.count(temp) > 0) { auto min = std::min(volume, all_start[temp]); volume -= min; all_start[temp] -= min; } } // clear with zero value clear_with_zeros(all_start); clear_with_zeros(all_end); #ifdef DEBUG dbg << "\nStart: "; for(const auto& x: all_start) { dbg << x << " "; } dbg << endl << endl << "End: "; for(const auto& x: all_end) { dbg << x << " "; } dbg << endl << endl; #endif if (all_start.size() == 0) { if (all_end.size() == 0) { return true; } return false; } if (all_end.size() == 0) { return false; } if (all_start.begin()->first > all_end.begin()->first) { return false; } if (all_start.rbegin()->first < all_end.rbegin()->first) { return false; } { rational power_total_start, power_total_end; for (const auto&[temp, volume]: all_start) { power_total_start += temp * volume; } for (const auto&[temp, volume]: all_end) { power_total_end += temp * volume; } if (power_total_start != power_total_end) { return false; } } while (all_end.size() > 1 && all_start.size() > 1) { dbg << endl; auto now = all_end.begin(); #ifdef DEBUG dbg << "Trying now " << *now << endl; dbg << "Using: "; for(const auto x: all_start) { dbg << x << " "; } dbg << endl; #endif auto s1 = all_start.begin(), s2 = s1; s2++; #define TEMP(x) (x->first) #define VOL(x) (x->second) if (TEMP(now) < TEMP(s1)) { return false; } if (TEMP(now) > TEMP(s2)) { // merge s1 and s2 auto vol = VOL(s1) + VOL(s2); auto temp = (TEMP(s1) * VOL(s1) + TEMP(s2) * VOL(s2)) / vol; all_start[temp] = vol; dbg << "Merge " << *s1 << " and " << *s2 << " into " << temp << ", " << vol << endl; all_start.erase(s1); all_start.erase(s2); continue; } // here, TEMP(s1) < TEMP(now) < TEMP(s2) // calculate how much to take from s1 and s2 auto Ax1 = VOL(now) * (TEMP(s2) - TEMP(now)) / (TEMP(s2) - TEMP(s1)); auto Ax2 = VOL(now) * (TEMP(now) - TEMP(s1)) / (TEMP(s2) - TEMP(s1)); dbg << "Best to take " << Ax1 << " from first, and " << Ax2 << " from second" << endl; auto A1 = Ax1; auto A2 = Ax2; if (Ax1 > VOL(s1)) { A1 = VOL(s1); A2 = Ax2 * VOL(s1) / Ax1; } Ax1 = A1; Ax2 = A2; if (Ax2 > VOL(s2)) { A1 = Ax1 * VOL(s2) / Ax2; A2 = VOL(s2); } assert(Ax1 <= VOL(s1)); dbg << "After reduction: " << A1 << ", " << A2 << endl; VOL(s1) -= A1; VOL(s2) -= A2; VOL(now) -= (A1 + A2); if (VOL(s1) == 0ull) { dbg << "dropping first!" << endl; all_start.erase(s1); } if (VOL(s2) == 0ull) { dbg << "dropping second!" << endl; all_start.erase(s2); } if (VOL(now) == 0ull) { dbg << "dropping requirement!" << endl; all_end.erase(now); } } #ifdef DEBUG dbg << "\nAt the end:\n"; dbg << "Start: "; for(const auto& x: all_start) { dbg << x << " "; } dbg << endl << endl << "End: "; for(const auto& x: all_end) { dbg << x << " "; } dbg << endl << endl; #endif rational power_total_start, power_total_end; rational volume_total_start, volume_total_end; for(const auto& [temp, volume]: all_start) { power_total_start += temp*volume; volume_total_start += volume; } for(const auto& [temp, volume]: all_end) { power_total_end += temp*volume; volume_total_end += volume; } if (power_total_start == power_total_end && volume_total_start == volume_total_end) { return true; } else { return false; } } int main() { // std::ios_base::sync_with_stdio(false); // std::cin.tie(nullptr); int Z; cin >> Z; while(Z--) { if (solve()) { cout << "TAK\n"; } else { cout << "NIE\n"; } } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 | #include <iostream> #include <set> #include <map> #include <limits> #include <vector> #include <iomanip> // for std::setw #include <ios> // for std::noskipws, streamsize #include <istream> // for std::istream #include <ostream> // for std::ostream #include <sstream> // for std::ostringstream #include <cstddef> // for NULL #include <stdexcept> // for std::domain_error #include <string> // for std::string implicit constructor #include <cstdlib> // for std::abs #include <limits> // for std::numeric_limits #include<type_traits> using namespace std; # define throw(x) throw(x) namespace boost { template<bool B, class T = void> struct enable_if_c { typedef T type; }; template<class T> struct enable_if_c<false, T> { }; template<bool B, class T = void> struct disable_if_c { typedef T type; }; template<class T> struct disable_if_c<true, T> { }; }; #include <cassert> #include <climits> #include <iterator> #include <algorithm> #include <limits> #include <type_traits> namespace boost { template <class I> class rational; namespace integer { namespace gcd_detail{ template <class T> inline constexpr T constexpr_min(T const& a, T const& b) noexcept { return a < b ? a : b; } template <class T> inline constexpr auto constexpr_swap(T&a, T& b) noexcept -> decltype(a.swap(b)) { return a.swap(b); } template <class T, class U> inline constexpr void constexpr_swap(T&a, U& b...) noexcept { T t(static_cast<T&&>(a)); a = static_cast<T&&>(b); b = static_cast<T&&>(t); } template <class T, bool a = std::is_unsigned<T>::value || (std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_signed)> struct gcd_traits_abs_defaults { inline static constexpr const T& abs(const T& val) noexcept { return val; } }; template <class T> struct gcd_traits_abs_defaults<T, false> { inline static T constexpr abs(const T& val) noexcept { // This sucks, but std::abs is not constexpr :( return val < T(0) ? -val : val; } }; enum method_type { method_euclid = 0, method_binary = 1, method_mixed = 2 }; struct any_convert { template <class T> any_convert(const T&); }; struct unlikely_size { char buf[9973]; }; unlikely_size operator <<= (any_convert, any_convert); unlikely_size operator >>= (any_convert, any_convert); template <class T> struct gcd_traits_defaults : public gcd_traits_abs_defaults<T> { inline static constexpr unsigned make_odd(T& val) noexcept { unsigned r = 0; while(0 == (val & 1u)) { val >>= 1; ++r; } return r; } inline static constexpr bool less(const T& a, const T& b) noexcept { return a < b; } static T& get_value(); static const bool has_operator_left_shift_equal = sizeof(get_value() <<= 2) != sizeof(unlikely_size); static const bool has_operator_right_shift_equal = sizeof(get_value() >>= 2) != sizeof(unlikely_size); static const method_type method = std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && has_operator_left_shift_equal && has_operator_right_shift_equal ? method_mixed : method_euclid; }; // // Default gcd_traits just inherits from defaults: // template <class T> struct gcd_traits : public gcd_traits_defaults<T> {}; // // The Mixed Binary Euclid Algorithm // Sidi Mohamed Sedjelmaci // Electronic Notes in Discrete Mathematics 35 (2009) 169-176 // template <class T> constexpr T mixed_binary_gcd(T u, T v) noexcept { if(gcd_traits<T>::less(u, v)) constexpr_swap(u, v); unsigned shifts = 0; if(u == T(0)) return v; if(v == T(0)) return u; shifts = constexpr_min(gcd_traits<T>::make_odd(u), gcd_traits<T>::make_odd(v)); while(gcd_traits<T>::less(1, v)) { u %= v; v -= u; if(u == T(0)) return v << shifts; if(v == T(0)) return u << shifts; gcd_traits<T>::make_odd(u); gcd_traits<T>::make_odd(v); if(gcd_traits<T>::less(u, v)) constexpr_swap(u, v); } return (v == 1 ? v : u) << shifts; } /** Stein gcd (aka 'binary gcd') * * From Mathematics to Generic Programming, Alexander Stepanov, Daniel Rose */ template <typename SteinDomain> constexpr SteinDomain Stein_gcd(SteinDomain m, SteinDomain n) noexcept { assert(m >= 0); assert(n >= 0); if (m == SteinDomain(0)) return n; if (n == SteinDomain(0)) return m; // m > 0 && n > 0 unsigned d_m = gcd_traits<SteinDomain>::make_odd(m); unsigned d_n = gcd_traits<SteinDomain>::make_odd(n); // odd(m) && odd(n) while (m != n) { if (n > m) constexpr_swap(n, m); m -= n; gcd_traits<SteinDomain>::make_odd(m); } // m == n m <<= constexpr_min(d_m, d_n); return m; } /** Euclidean algorithm * * From Mathematics to Generic Programming, Alexander Stepanov, Daniel Rose * */ template <typename EuclideanDomain> inline constexpr EuclideanDomain Euclid_gcd(EuclideanDomain a, EuclideanDomain b) noexcept { while (b != EuclideanDomain(0)) { a %= b; constexpr_swap(a, b); } return a; } template <typename T> inline constexpr typename enable_if_c<gcd_traits<T>::method == method_mixed, T>::type optimal_gcd_select(T const &a, T const &b) noexcept { return gcd_detail::mixed_binary_gcd(a, b); } template <typename T> inline constexpr typename enable_if_c<gcd_traits<T>::method == method_binary, T>::type optimal_gcd_select(T const &a, T const &b) noexcept { return gcd_detail::Stein_gcd(a, b); } template <typename T> inline constexpr typename enable_if_c<gcd_traits<T>::method == method_euclid, T>::type optimal_gcd_select(T const &a, T const &b) noexcept { return gcd_detail::Euclid_gcd(a, b); } template <class T> inline constexpr T lcm_imp(const T& a, const T& b) noexcept { T temp = boost::integer::gcd_detail::optimal_gcd_select(a, b); return (temp != T(0)) ? T(a / temp * b) : T(0); } } // namespace detail template <typename Integer> inline constexpr Integer gcd(Integer const &a, Integer const &b) noexcept { if(a == (std::numeric_limits<Integer>::min)()) return a == static_cast<Integer>(0) ? gcd_detail::gcd_traits<Integer>::abs(b) : boost::integer::gcd(static_cast<Integer>(a % b), b); else if (b == (std::numeric_limits<Integer>::min)()) return b == static_cast<Integer>(0) ? gcd_detail::gcd_traits<Integer>::abs(a) : boost::integer::gcd(a, static_cast<Integer>(b % a)); return gcd_detail::optimal_gcd_select(static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(a)), static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(b))); } template <typename Integer> inline constexpr Integer lcm(Integer const &a, Integer const &b) noexcept { return gcd_detail::lcm_imp(static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(a)), static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(b))); } } // namespace integer } // namespace boost namespace boost { namespace rational_detail{ template <class FromInt, class ToInt> struct is_compatible_integer { static const bool value = ((std::numeric_limits<FromInt>::is_specialized && std::numeric_limits<FromInt>::is_integer && (std::numeric_limits<FromInt>::digits <= std::numeric_limits<ToInt>::digits) && (std::numeric_limits<FromInt>::radix == std::numeric_limits<ToInt>::radix) && ((std::numeric_limits<FromInt>::is_signed == false) || (std::numeric_limits<ToInt>::is_signed == true)) && is_convertible<FromInt, ToInt>::value) || is_same<FromInt, ToInt>::value) || (is_class<ToInt>::value && is_class<FromInt>::value && is_convertible<FromInt, ToInt>::value); }; } class bad_rational : public std::domain_error { public: explicit bad_rational() : std::domain_error("bad rational: zero denominator") {} explicit bad_rational( char const *what ) : std::domain_error( what ) {} }; template <typename IntType> class rational { // Class-wide pre-conditions static_assert( ::std::numeric_limits<IntType>::is_specialized ); // Helper types using param_type = IntType; struct helper { IntType parts[2]; }; typedef IntType (helper::* bool_type)[2]; public: // Component type typedef IntType int_type; constexpr rational() : num(0), den(1) {} template <class T> constexpr rational(const T& n) : num(n), den(1) {} template <class T, class U> constexpr rational(const T& n, const U& d) : num(n), den(d) { normalize(); } template < typename NewType > constexpr explicit rational(rational<NewType> const &r, typename enable_if_c<rational_detail::is_compatible_integer<NewType, IntType>::value>::type const* = 0) : num(r.numerator()), den(is_normalized(int_type(r.numerator()), int_type(r.denominator())) ? r.denominator() : (throw(bad_rational("bad rational: denormalized conversion")), 0)){} template < typename NewType > constexpr explicit rational(rational<NewType> const &r, typename disable_if_c<rational_detail::is_compatible_integer<NewType, IntType>::value>::type const* = 0) : num(r.numerator()), den(is_normalized(int_type(r.numerator()), int_type(r.denominator())) && is_safe_narrowing_conversion(r.denominator()) && is_safe_narrowing_conversion(r.numerator()) ? r.denominator() : (throw(bad_rational("bad rational: denormalized conversion")), 0)){} // Default copy constructor and assignment are fine // Add assignment from IntType template <class T> constexpr typename enable_if_c< rational_detail::is_compatible_integer<T, IntType>::value, rational & >::type operator=(const T& n) { return assign(static_cast<IntType>(n), static_cast<IntType>(1)); } // Assign in place template <class T, class U> constexpr typename enable_if_c< rational_detail::is_compatible_integer<T, IntType>::value && rational_detail::is_compatible_integer<U, IntType>::value, rational & >::type assign(const T& n, const U& d) { return *this = rational<IntType>(static_cast<IntType>(n), static_cast<IntType>(d)); } // // The following overloads should probably *not* be provided - // but are provided for backwards compatibity reasons only. // These allow for construction/assignment from types that // are wider than IntType only if there is an implicit // conversion from T to IntType, they will throw a bad_rational // if the conversion results in loss of precision or undefined behaviour. // template <class T> constexpr rational(const T& n, typename enable_if_c< std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && !rational_detail::is_compatible_integer<T, IntType>::value && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) && is_convertible<T, IntType>::value >::type const* = 0) { assign(n, static_cast<T>(1)); } template <class T, class U> constexpr rational(const T& n, const U& d, typename enable_if_c< (!rational_detail::is_compatible_integer<T, IntType>::value || !rational_detail::is_compatible_integer<U, IntType>::value) && std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) && is_convertible<T, IntType>::value && std::numeric_limits<U>::is_specialized && std::numeric_limits<U>::is_integer && (std::numeric_limits<U>::radix == std::numeric_limits<IntType>::radix) && is_convertible<U, IntType>::value >::type const* = 0) { assign(n, d); } template <class T> constexpr typename enable_if_c< std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && !rational_detail::is_compatible_integer<T, IntType>::value && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) && is_convertible<T, IntType>::value, rational & >::type operator=(const T& n) { return assign(n, static_cast<T>(1)); } template <class T, class U> constexpr typename enable_if_c< (!rational_detail::is_compatible_integer<T, IntType>::value || !rational_detail::is_compatible_integer<U, IntType>::value) && std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && (std::numeric_limits<T>::radix == std::numeric_limits<IntType>::radix) && is_convertible<T, IntType>::value && std::numeric_limits<U>::is_specialized && std::numeric_limits<U>::is_integer && (std::numeric_limits<U>::radix == std::numeric_limits<IntType>::radix) && is_convertible<U, IntType>::value, rational & >::type assign(const T& n, const U& d) { if(!is_safe_narrowing_conversion(n) || !is_safe_narrowing_conversion(d)) throw(bad_rational()); return *this = rational<IntType>(static_cast<IntType>(n), static_cast<IntType>(d)); } // Access to representation constexpr const IntType& numerator() const { return num; } constexpr const IntType& denominator() const { return den; } // Arithmetic assignment operators constexpr rational& operator+= (const rational& r); constexpr rational& operator-= (const rational& r); constexpr rational& operator*= (const rational& r); constexpr rational& operator/= (const rational& r); template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator+= (const T& i) { num += i * den; return *this; } template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator-= (const T& i) { num -= i * den; return *this; } template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator*= (const T& i) { // Avoid overflow and preserve normalization IntType gcd = integer::gcd(static_cast<IntType>(i), den); num *= i / gcd; den /= gcd; return *this; } template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, rational&>::type operator/= (const T& i) { // Avoid repeated construction IntType const zero(0); if(i == zero) throw(bad_rational()); if(num == zero) return *this; // Avoid overflow and preserve normalization IntType const gcd = integer::gcd(num, static_cast<IntType>(i)); num /= gcd; den *= i / gcd; if(den < zero) { num = -num; den = -den; } return *this; } // Increment and decrement constexpr const rational& operator++() { num += den; return *this; } constexpr const rational& operator--() { num -= den; return *this; } constexpr rational operator++(int) { rational t(*this); ++(*this); return t; } constexpr rational operator--(int) { rational t(*this); --(*this); return t; } // Operator not constexpr bool operator!() const { return !num; } // Boolean conversion constexpr operator bool_type() const { return operator !() ? 0 : &helper::parts; } // Comparison operators constexpr bool operator< (const rational& r) const; constexpr bool operator> (const rational& r) const { return r < *this; } constexpr bool operator== (const rational& r) const; template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator< (const T& i) const { // Avoid repeated construction int_type const zero(0); // Break value into mixed-fraction form, w/ always-nonnegative remainder assert(this->den > zero); int_type q = this->num / this->den, r = this->num % this->den; while(r < zero) { r += this->den; --q; } // Compare with just the quotient, since the remainder always bumps the // value up. [Since q = floor(n/d), and if n/d < i then q < i, if n/d == i // then q == i, if n/d == i + r/d then q == i, and if n/d >= i + 1 then // q >= i + 1 > i; therefore n/d < i iff q < i.] return q < i; } template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator>(const T& i) const { return operator==(i) ? false : !operator<(i); } template <class T> constexpr typename boost::enable_if_c<rational_detail::is_compatible_integer<T, IntType>::value, bool>::type operator== (const T& i) const { return ((den == IntType(1)) && (num == i)); } private: // Implementation - numerator and denominator (normalized). // Other possibilities - separate whole-part, or sign, fields? IntType num; IntType den; // Helper functions static constexpr int_type inner_gcd( param_type a, param_type b, int_type const &zero = int_type(0) ) { return b == zero ? a : inner_gcd(b, a % b, zero); } static constexpr int_type inner_abs( param_type x, int_type const &zero = int_type(0) ) { return x < zero ? -x : +x; } // Representation note: Fractions are kept in normalized form at all // times. normalized form is defined as gcd(num,den) == 1 and den > 0. // In particular, note that the implementation of abs() below relies // on den always being positive. constexpr bool test_invariant() const; constexpr void normalize(); static constexpr bool is_normalized( param_type n, param_type d, int_type const &zero = int_type(0), int_type const &one = int_type(1) ) { return d > zero && ( n != zero || d == one ) && inner_abs( inner_gcd(n, d, zero), zero ) == one; } // // Conversion checks: // // (1) From an unsigned type with more digits than IntType: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val) { return val < (T(1) << std::numeric_limits<IntType>::digits); } // // (2) From a signed type with more digits than IntType, and IntType also signed: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T& val) { // Note that this check assumes IntType has a 2's complement representation, // we don't want to try to convert a std::numeric_limits<IntType>::min() to // a T because that conversion may not be allowed (this happens when IntType // is from Boost.Multiprecision). return (val < (T(1) << std::numeric_limits<IntType>::digits)) && (val >= -(T(1) << std::numeric_limits<IntType>::digits)); } // // (3) From a signed type with more digits than IntType, and IntType unsigned: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits > std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val) { return (val < (T(1) << std::numeric_limits<IntType>::digits)) && (val >= 0); } // // (4) From a signed type with fewer digits than IntType, and IntType unsigned: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T& val) { return val >= 0; } // // (5) From an unsigned type with fewer digits than IntType, and IntType signed: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T&) { return true; } // // (6) From an unsigned type with fewer digits than IntType, and IntType unsigned: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == false) && (std::numeric_limits<IntType>::is_signed == false), bool>::type is_safe_narrowing_conversion(const T&) { return true; } // // (7) From an signed type with fewer digits than IntType, and IntType signed: // template <class T> constexpr static typename boost::enable_if_c<(std::numeric_limits<T>::digits <= std::numeric_limits<IntType>::digits) && (std::numeric_limits<T>::is_signed == true) && (std::numeric_limits<IntType>::is_signed == true), bool>::type is_safe_narrowing_conversion(const T&) { return true; } }; // Unary plus and minus template <typename IntType> constexpr inline rational<IntType> operator+ (const rational<IntType>& r) { return r; } template <typename IntType> constexpr inline rational<IntType> operator- (const rational<IntType>& r) { return rational<IntType>(static_cast<IntType>(-r.numerator()), r.denominator()); } // Arithmetic assignment operators template <typename IntType> constexpr rational<IntType>& rational<IntType>::operator+= (const rational<IntType>& r) { // This calculation avoids overflow, and minimises the number of expensive // calculations. Thanks to Nickolay Mladenov for this algorithm. // // Proof: // We have to compute a/b + c/d, where gcd(a,b)=1 and gcd(b,c)=1. // Let g = gcd(b,d), and b = b1*g, d=d1*g. Then gcd(b1,d1)=1 // // The result is (a*d1 + c*b1) / (b1*d1*g). // Now we have to normalize this ratio. // Let's assume h | gcd((a*d1 + c*b1), (b1*d1*g)), and h > 1 // If h | b1 then gcd(h,d1)=1 and hence h|(a*d1+c*b1) => h|a. // But since gcd(a,b1)=1 we have h=1. // Similarly h|d1 leads to h=1. // So we have that h | gcd((a*d1 + c*b1) , (b1*d1*g)) => h|g // Finally we have gcd((a*d1 + c*b1), (b1*d1*g)) = gcd((a*d1 + c*b1), g) // Which proves that instead of normalizing the result, it is better to // divide num and den by gcd((a*d1 + c*b1), g) // Protect against self-modification IntType r_num = r.num; IntType r_den = r.den; IntType g = integer::gcd(den, r_den); den /= g; // = b1 from the calculations above num = num * (r_den / g) + r_num * den; g = integer::gcd(num, g); num /= g; den *= r_den/g; return *this; } template <typename IntType> constexpr rational<IntType>& rational<IntType>::operator-= (const rational<IntType>& r) { // Protect against self-modification IntType r_num = r.num; IntType r_den = r.den; // This calculation avoids overflow, and minimises the number of expensive // calculations. It corresponds exactly to the += case above IntType g = integer::gcd(den, r_den); den /= g; num = num * (r_den / g) - r_num * den; g = integer::gcd(num, g); num /= g; den *= r_den/g; return *this; } template <typename IntType> constexpr rational<IntType>& rational<IntType>::operator*= (const rational<IntType>& r) { // Protect against self-modification IntType r_num = r.num; IntType r_den = r.den; // Avoid overflow and preserve normalization IntType gcd1 = integer::gcd(num, r_den); IntType gcd2 = integer::gcd(r_num, den); num = (num/gcd1) * (r_num/gcd2); den = (den/gcd2) * (r_den/gcd1); return *this; } template <typename IntType> constexpr rational<IntType>& rational<IntType>::operator/= (const rational<IntType>& r) { // Protect against self-modification IntType r_num = r.num; IntType r_den = r.den; // Avoid repeated construction IntType zero(0); // Trap division by zero if (r_num == zero) throw(bad_rational()); if (num == zero) return *this; // Avoid overflow and preserve normalization IntType gcd1 = integer::gcd(num, r_num); IntType gcd2 = integer::gcd(r_den, den); num = (num/gcd1) * (r_den/gcd2); den = (den/gcd2) * (r_num/gcd1); if (den < zero) { num = -num; den = -den; } return *this; } // // Non-member operators: previously these were provided by Boost.Operator, but these had a number of // drawbacks, most notably, that in order to allow inter-operability with IntType code such as this: // // rational<int> r(3); // assert(r == 3.5); // compiles and passes!! // // Happens to be allowed as well :-( // // There are three possible cases for each operator: // 1) rational op rational. // 2) rational op integer // 3) integer op rational // Cases (1) and (2) are folded into the one function. // template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type operator + (const rational<IntType>& a, const Arg& b) { rational<IntType> t(a); return t += b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type operator + (const Arg& b, const rational<IntType>& a) { rational<IntType> t(a); return t += b; } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type operator - (const rational<IntType>& a, const Arg& b) { rational<IntType> t(a); return t -= b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type operator - (const Arg& b, const rational<IntType>& a) { rational<IntType> t(a); return -(t -= b); } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type operator * (const rational<IntType>& a, const Arg& b) { rational<IntType> t(a); return t *= b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type operator * (const Arg& b, const rational<IntType>& a) { rational<IntType> t(a); return t *= b; } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, rational<IntType> >::type operator / (const rational<IntType>& a, const Arg& b) { rational<IntType> t(a); return t /= b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, rational<IntType> >::type operator / (const Arg& b, const rational<IntType>& a) { rational<IntType> t(b); return t /= a; } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type operator <= (const rational<IntType>& a, const Arg& b) { return !(a > b); } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator <= (const Arg& b, const rational<IntType>& a) { return a >= b; } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type operator >= (const rational<IntType>& a, const Arg& b) { return !(a < b); } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator >= (const Arg& b, const rational<IntType>& a) { return a <= b; } template <class IntType, class Arg> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value || is_same<rational<IntType>, Arg>::value, bool>::type operator != (const rational<IntType>& a, const Arg& b) { return !(a == b); } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator != (const Arg& b, const rational<IntType>& a) { return !(b == a); } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator < (const Arg& b, const rational<IntType>& a) { return a > b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator > (const Arg& b, const rational<IntType>& a) { return a < b; } template <class Arg, class IntType> constexpr inline typename boost::enable_if_c < rational_detail::is_compatible_integer<Arg, IntType>::value, bool>::type operator == (const Arg& b, const rational<IntType>& a) { return a == b; } // Comparison operators template <typename IntType> constexpr bool rational<IntType>::operator< (const rational<IntType>& r) const { // Avoid repeated construction int_type const zero( 0 ); // This should really be a class-wide invariant. The reason for these // checks is that for 2's complement systems, INT_MIN has no corresponding // positive, so negating it during normalization keeps it INT_MIN, which // is bad for later calculations that assume a positive denominator. assert( this->den > zero ); assert( r.den > zero ); // Determine relative order by expanding each value to its simple continued // fraction representation using the Euclidian GCD algorithm. struct { int_type n, d, q, r; } ts = { this->num, this->den, static_cast<int_type>(this->num / this->den), static_cast<int_type>(this->num % this->den) }, rs = { r.num, r.den, static_cast<int_type>(r.num / r.den), static_cast<int_type>(r.num % r.den) }; unsigned reverse = 0u; // Normalize negative moduli by repeatedly adding the (positive) denominator // and decrementing the quotient. Later cycles should have all positive // values, so this only has to be done for the first cycle. (The rules of // C++ require a nonnegative quotient & remainder for a nonnegative dividend // & positive divisor.) while ( ts.r < zero ) { ts.r += ts.d; --ts.q; } while ( rs.r < zero ) { rs.r += rs.d; --rs.q; } // Loop through and compare each variable's continued-fraction components for ( ;; ) { // The quotients of the current cycle are the continued-fraction // components. Comparing two c.f. is comparing their sequences, // stopping at the first difference. if ( ts.q != rs.q ) { // Since reciprocation changes the relative order of two variables, // and c.f. use reciprocals, the less/greater-than test reverses // after each index. (Start w/ non-reversed @ whole-number place.) return reverse ? ts.q > rs.q : ts.q < rs.q; } // Prepare the next cycle reverse ^= 1u; if ( (ts.r == zero) || (rs.r == zero) ) { // At least one variable's c.f. expansion has ended break; } ts.n = ts.d; ts.d = ts.r; ts.q = ts.n / ts.d; ts.r = ts.n % ts.d; rs.n = rs.d; rs.d = rs.r; rs.q = rs.n / rs.d; rs.r = rs.n % rs.d; } // Compare infinity-valued components for otherwise equal sequences if ( ts.r == rs.r ) { // Both remainders are zero, so the next (and subsequent) c.f. // components for both sequences are infinity. Therefore, the sequences // and their corresponding values are equal. return false; } else { #ifdef BOOST_MSVC #pragma warning(push) #pragma warning(disable:4800) #endif // Exactly one of the remainders is zero, so all following c.f. // components of that variable are infinity, while the other variable // has a finite next c.f. component. So that other variable has the // lesser value (modulo the reversal flag!). return ( ts.r != zero ) != static_cast<bool>( reverse ); #ifdef BOOST_MSVC #pragma warning(pop) #endif } } template <typename IntType> constexpr inline bool rational<IntType>::operator== (const rational<IntType>& r) const { return ((num == r.num) && (den == r.den)); } // Invariant check template <typename IntType> constexpr inline bool rational<IntType>::test_invariant() const { return ( this->den > int_type(0) ) && ( integer::gcd(this->num, this->den) == int_type(1) ); } // Normalisation template <typename IntType> constexpr void rational<IntType>::normalize() { // Avoid repeated construction IntType zero(0); if (den == zero) throw(bad_rational()); // Handle the case of zero separately, to avoid division by zero if (num == zero) { den = IntType(1); return; } IntType g = integer::gcd(num, den); num /= g; den /= g; if (den < -(std::numeric_limits<IntType>::max)()) { throw(bad_rational("bad rational: non-zero singular denominator")); } // Ensure that the denominator is positive if (den < zero) { num = -num; den = -den; } assert( this->test_invariant() ); } #ifndef BOOST_NO_IOSTREAM namespace detail { // A utility class to reset the format flags for an istream at end // of scope, even in case of exceptions struct resetter { resetter(std::istream& is) : is_(is), f_(is.flags()) {} ~resetter() { is_.flags(f_); } std::istream& is_; std::istream::fmtflags f_; // old GNU c++ lib has no ios_base }; } // Input and output template <typename IntType> std::istream& operator>> (std::istream& is, rational<IntType>& r) { using std::ios; IntType n = IntType(0), d = IntType(1); char c = 0; detail::resetter sentry(is); if ( is >> n ) { if ( is.get(c) ) { if ( c == '/' ) { if ( is >> std::noskipws >> d ) try { r.assign( n, d ); } catch ( bad_rational & ) { // normalization fail try { is.setstate(ios::failbit); } catch ( ... ) {} // don't throw ios_base::failure... if ( is.exceptions() & ios::failbit ) throw; // ...but the original exception instead // ELSE: suppress the exception, use just error flags } } else is.setstate( ios::failbit ); } } return is; } // Add manipulators for output format? template <typename IntType> std::ostream& operator<< (std::ostream& os, const rational<IntType>& r) { // The slash directly precedes the denominator, which has no prefixes. std::ostringstream ss; ss.copyfmt( os ); ss.tie( NULL ); ss.exceptions( std::ios::goodbit ); ss.width( 0 ); ss << std::noshowpos << std::noshowbase << '/' << r.denominator(); // The numerator holds the showpos, internal, and showbase flags. std::string const tail = ss.str(); std::streamsize const w = os.width() - static_cast<std::streamsize>( tail.size() ); ss.clear(); ss.str( "" ); ss.flags( os.flags() ); ss << std::setw( w < 0 || (os.flags() & std::ios::adjustfield) != std::ios::internal ? 0 : w ) << r.numerator(); return os << ss.str() + tail; } #endif // BOOST_NO_IOSTREAM // Type conversion template <typename T, typename IntType> constexpr inline T rational_cast(const rational<IntType>& src) { return static_cast<T>(src.numerator())/static_cast<T>(src.denominator()); } // Do not use any abs() defined on IntType - it isn't worth it, given the // difficulties involved (Koenig lookup required, there may not *be* an abs() // defined, etc etc). template <typename IntType> constexpr inline rational<IntType> abs(const rational<IntType>& r) { return r.numerator() >= IntType(0)? r: -r; } } // namespace boost using rational = boost::rational<unsigned long long>; struct Teacup { unsigned long long temperature; rational volume; Teacup(int temperature, rational volume) : temperature(temperature), volume(volume) {} bool operator==(const Teacup& second) const noexcept { return this->temperature == second.temperature; } bool operator<(const Teacup& second) const noexcept { return this->temperature < second.temperature; } }; ostream& operator<<(ostream& os, const Teacup& teacup) { os << "(t: " << teacup.temperature << ", v: " << teacup.volume << ")"; return os; } //ostream& operator<<(ostream& os, const pair<int,int>& teacup) //{ // os << "(t: " << teacup.first << ", v: " << teacup.second << ")"; // return os; //} ostream& operator<<(ostream& os, const pair<rational, rational>& teacup) { os << "(t: " << teacup.first << ", v: " << teacup.second << ")"; return os; } //#define DEBUG #ifdef DEBUG #define dbg cerr #else #define dbg 0 && cerr #endif template<typename T> void clear_with_zeros(T& mapa) { std::vector<rational> keys_to_remove; for(const auto& [key, value]: mapa) { if (value == 0ull) { keys_to_remove.push_back(key); } } for (const auto& key: keys_to_remove) { mapa.erase(key); } } bool solve() { int n; cin >> n; map<rational, rational> all_start, all_end; for (int i = 0; i < n; ++i) { int l, start, end; cin >> l >> start >> end; if (all_start.count(1ull * start) == 0) { all_start[1ull * start] = 0; } if (all_end.count(1ull* end) == 0) { all_end[1ull* end] = 0; } all_start[1ull* start] += 1ull* l; all_end[1ull* end] += 1ull* l; } #ifdef DEBUG dbg << "Start: "; for(const auto& x: all_start) { dbg << x << " "; } dbg << endl << endl << "End: "; for(const auto& x: all_end) { dbg << x << " "; } dbg << endl << endl; #endif // satisfy correct cups for(auto& [temp, volume]: all_end) { if (all_start.count(temp) > 0) { auto min = std::min(volume, all_start[temp]); volume -= min; all_start[temp] -= min; } } // clear with zero value clear_with_zeros(all_start); clear_with_zeros(all_end); #ifdef DEBUG dbg << "\nStart: "; for(const auto& x: all_start) { dbg << x << " "; } dbg << endl << endl << "End: "; for(const auto& x: all_end) { dbg << x << " "; } dbg << endl << endl; #endif if (all_start.size() == 0) { if (all_end.size() == 0) { return true; } return false; } if (all_end.size() == 0) { return false; } if (all_start.begin()->first > all_end.begin()->first) { return false; } if (all_start.rbegin()->first < all_end.rbegin()->first) { return false; } { rational power_total_start, power_total_end; for (const auto&[temp, volume]: all_start) { power_total_start += temp * volume; } for (const auto&[temp, volume]: all_end) { power_total_end += temp * volume; } if (power_total_start != power_total_end) { return false; } } while (all_end.size() > 1 && all_start.size() > 1) { dbg << endl; auto now = all_end.begin(); #ifdef DEBUG dbg << "Trying now " << *now << endl; dbg << "Using: "; for(const auto x: all_start) { dbg << x << " "; } dbg << endl; #endif auto s1 = all_start.begin(), s2 = s1; s2++; #define TEMP(x) (x->first) #define VOL(x) (x->second) if (TEMP(now) < TEMP(s1)) { return false; } if (TEMP(now) > TEMP(s2)) { // merge s1 and s2 auto vol = VOL(s1) + VOL(s2); auto temp = (TEMP(s1) * VOL(s1) + TEMP(s2) * VOL(s2)) / vol; all_start[temp] = vol; dbg << "Merge " << *s1 << " and " << *s2 << " into " << temp << ", " << vol << endl; all_start.erase(s1); all_start.erase(s2); continue; } // here, TEMP(s1) < TEMP(now) < TEMP(s2) // calculate how much to take from s1 and s2 auto Ax1 = VOL(now) * (TEMP(s2) - TEMP(now)) / (TEMP(s2) - TEMP(s1)); auto Ax2 = VOL(now) * (TEMP(now) - TEMP(s1)) / (TEMP(s2) - TEMP(s1)); dbg << "Best to take " << Ax1 << " from first, and " << Ax2 << " from second" << endl; auto A1 = Ax1; auto A2 = Ax2; if (Ax1 > VOL(s1)) { A1 = VOL(s1); A2 = Ax2 * VOL(s1) / Ax1; } Ax1 = A1; Ax2 = A2; if (Ax2 > VOL(s2)) { A1 = Ax1 * VOL(s2) / Ax2; A2 = VOL(s2); } assert(Ax1 <= VOL(s1)); dbg << "After reduction: " << A1 << ", " << A2 << endl; VOL(s1) -= A1; VOL(s2) -= A2; VOL(now) -= (A1 + A2); if (VOL(s1) == 0ull) { dbg << "dropping first!" << endl; all_start.erase(s1); } if (VOL(s2) == 0ull) { dbg << "dropping second!" << endl; all_start.erase(s2); } if (VOL(now) == 0ull) { dbg << "dropping requirement!" << endl; all_end.erase(now); } } #ifdef DEBUG dbg << "\nAt the end:\n"; dbg << "Start: "; for(const auto& x: all_start) { dbg << x << " "; } dbg << endl << endl << "End: "; for(const auto& x: all_end) { dbg << x << " "; } dbg << endl << endl; #endif rational power_total_start, power_total_end; rational volume_total_start, volume_total_end; for(const auto& [temp, volume]: all_start) { power_total_start += temp*volume; volume_total_start += volume; } for(const auto& [temp, volume]: all_end) { power_total_end += temp*volume; volume_total_end += volume; } if (power_total_start == power_total_end && volume_total_start == volume_total_end) { return true; } else { return false; } } int main() { // std::ios_base::sync_with_stdio(false); // std::cin.tie(nullptr); int Z; cin >> Z; while(Z--) { if (solve()) { cout << "TAK\n"; } else { cout << "NIE\n"; } } } |