// https://github.com/2251799813685248/Competitive-Programming-Library #include #include #include #include #include #include #ifndef LIST__HPP_ #define LIST__HPP_ #include #include #include #include #include using uint = unsigned int; using ll = long long; using namespace std; template concept has_identity = requires (){T();}; template concept has_plus_operator = requires (T a, T b){a+b;}; template concept has_compare_operator = requires (T a, T b){a < b;}; template concept has_equal_operator = requires (T a, T b){a == b; a != b;}; /// @brief 動的配列 template class list{ public: using value_type = T; constexpr list(): sz_(0), max_sz_(0), A(nullptr){} constexpr list(uint sz): sz_(sz), max_sz_(sz){ if (sz == 0){A = nullptr; return;} if (sz > 214748367){cerr << "ValueError: too large or negative size" << endl; assert(false);} A = new T[sz_]{}; if (A == nullptr){cerr << "MomoryError: failed to allocate memory" << endl; assert(false);} } constexpr list(uint sz, T elem): sz_(sz), max_sz_(sz){ if (sz == 0){A = nullptr; return;} if (sz > 2147483647){cerr << "ValueError: too large or negative size" << endl; assert(false);} A = new T[sz_]{}; if (A == nullptr){cerr << "MemoryError: failed to allocate memory" << endl; assert(false);} for (int i = 0; i < sz_; i++){ A[i] = elem; } } constexpr list(initializer_list init): sz_(init.size()), max_sz_(init.size()){ A = new T[sz_]{}; if (A == nullptr){cerr << "MemoryError: failed to allocate memory" << endl; assert(false);} for (int i = 0; i < sz_; i++){ A[i] = *(init.begin()+i); } }; // constexpr list(const range& r){ // if (r.step_ == 0){cerr << "ValueError: step argument must not be zero" << endl; assert(false);} // if (r.step_ > 0){ // int imax = r.begin_ >= r.end_ ? 0 : (r.end_-r.begin_+r.step_-1)/r.step_; // sz_ = imax; // max_sz_ = imax; // A = new T[sz_]{}; // if (A == nullptr){cerr << "MemoryError: failed to allocate memory" << endl; assert(false);} // for (int i = 0; i < imax; i++){ // int target = r.begin_+r.step_*i; // A[i] = target; // } // } // else{ // int imax = r.end_ >= r.begin_ ? 0 : (r.begin_-r.end_-r.step_-1)/(-r.step_); // sz_ = imax; // max_sz_ = imax; // A = new T[sz_]{}; // if (A == nullptr){cerr << "MemoryError: failed to allocate memory" << endl; assert(false);} // for (int i = 0; i < imax; i++){ // int target = r.begin_+r.step_*i; // A[i] = target; // } // } // } constexpr list(const list& other): sz_(other.sz_), max_sz_(other.max_sz_){ A = new T[max_sz_]{}; for (int i = 0; i < sz_; i++){ A[i] = other.A[i]; } } constexpr list(list&& other) noexcept : sz_(other.sz_), max_sz_(other.max_sz_){ A = other.A; other.sz_ = 0; other.max_sz_ = 0; other.A = nullptr; } constexpr ~list() { if (A != nullptr){ delete[] A; } } class iterator{ public: using difference_type = ll; using value_type = T; using pointer = T*; using reference = T&; using iterator_category = std::random_access_iterator_tag; iterator() = delete; constexpr iterator(const list* listptr_init, const int &idx_init): listptr(listptr_init), idx(idx_init){} inline constexpr value_type& operator* () const {return listptr->A[this->check_idx()];} inline constexpr value_type* operator->() const {return &listptr->A[this->check_idx()];} inline constexpr bool operator==(const iterator &other) const {return idx == other.idx;} inline constexpr bool operator!=(const iterator &other) const {return idx != other.idx;} inline constexpr bool operator<(const iterator &other) const {return idx < other.idx;} inline constexpr bool operator>(const iterator &other) const {return idx > other.idx;} inline constexpr bool operator<=(const iterator &other) const {return idx <= other.idx;} inline constexpr bool operator>=(const iterator &other) const {return idx >= other.idx;} inline constexpr iterator operator++(){ this->idx++; return *this; } inline constexpr iterator operator++(int){ iterator temp = *this; this->idx++; return temp; } inline constexpr iterator operator--(){ this->idx--; return *this; } inline constexpr iterator operator--(int){ iterator temp = *this; this->idx--; return temp; } inline constexpr iterator& operator+=(int amount){ this->idx += amount; return *this; } inline constexpr iterator operator+(int amount) const { iterator temp = *this; temp.idx += amount; return temp; } inline constexpr iterator& operator-=(const int &amount){ this->idx -= amount; return *this; } inline constexpr iterator operator-(const int &amount) const{ iterator temp = *this; temp.idx -= amount; return temp; } inline constexpr difference_type operator-(const iterator &other) const{ return idx - other.idx; } inline constexpr int check_idx() const { if (idx < 0 || idx >= listptr->sz_){ cerr << "IteratorIndexError: index out of range. current size: " << listptr->sz_ << " target index: " << idx << endl; assert(false); } return idx; } inline constexpr int check_idx_tolerate_end() const { if (idx < 0 || idx > listptr->sz_){ cerr << "IteratorIndexError: index out of range(out of end). current size: " << listptr->sz_ << " target index: " << idx << endl; assert(false); } return idx; } private: const list* listptr; int idx; }; inline constexpr iterator begin(){return iterator(this, 0);} inline constexpr iterator begin() const {return iterator(this, 0);} inline constexpr iterator end(){return iterator(this, sz_);} inline constexpr iterator end() const {return iterator(this, sz_);} inline constexpr list& operator=(const list& other){ if (this == &other){return *this;} sz_ = other.sz_; max_sz_ = other.max_sz_; delete[] A; A = new T[max_sz_]{}; for (int i = 0; i < sz_; i++){ A[i] = other.A[i]; } return *this; } inline constexpr list& operator=(list&& other) noexcept { if (this == &other){return *this;} delete[] A; sz_ = other.sz_; max_sz_ = other.max_sz_; A = other.A; other.sz_ = 0; other.max_sz_ = 0; other.A = nullptr; return *this; } inline constexpr bool operator==(const list& other) const { if (sz_ != other.sz_){return false;} bool res = true; for (int i = 0; i < sz_; i++){ if (A[i] != other.A[i]){ res = false; break; } } return res; } inline constexpr bool operator!=(const list& other) const { return !(this->operator==(other)); } inline constexpr bool operator<(const list& other) const { int lcp_back = 0; for (int i = 0, sz2 = min(sz_, other.sz_); i < sz2; i++){ if (A[i] != other.A[i]){break;} lcp_back++; } if (lcp_back == sz_ && lcp_back == other.sz_){return false;} else if (lcp_back == sz_){return true;} else if (lcp_back == other.sz_){return false;} else{return A[lcp_back] < other.A[lcp_back];} } inline constexpr bool operator<=(const list& other) const { int lcp_back = 0; for (int i = 0, sz2 = min(sz_, other.sz_); i < sz2; i++){ if (A[i] != other.A[i]){break;} lcp_back++; } if (lcp_back == sz_ && lcp_back == other.sz_){return true;} else if (lcp_back == sz_){return true;} else if (lcp_back == other.sz_){return false;} else{return A[lcp_back] < other.A[lcp_back];} } inline constexpr bool operator>(const list& other) const {return other < *this;} inline constexpr bool operator>=(const list& other) const {return other <= *this;} inline constexpr list& operator+=(const list& other){ for (int i = 0, sz2 = other.size(); i < sz2; i++){ append(other.A[i]); } return *this; } inline constexpr list operator+(const list& other) const { return list(*this) += other; } inline constexpr list& operator+=(const T& val){ append(val); return *this; } inline constexpr list operator+(const T& val) const { return list(*this) += val; } inline constexpr void append(const T& val){ if (sz_ < max_sz_){ A[sz_] = val; sz_++; } else{ if (max_sz_ < 2){max_sz_ = 2;} else{max_sz_ += max_sz_>>1;} auto B = new T[max_sz_]{}; B[sz_] = val; for (int i = 0; i < sz_; i++){B[i] = std::move(A[i]);} sz_++; delete[] A; A = B; } } inline constexpr void append(T&& val){ if (sz_ < max_sz_){ A[sz_] = std::move(val); sz_++; } else{ if (max_sz_ < 2){max_sz_ = 2;} else{max_sz_ += max_sz_>>1;} auto B = new T[max_sz_]{}; B[sz_] = std::move(val); for (int i = 0; i < sz_; i++){B[i] = std::move(A[i]);} sz_++; delete[] A; A = B; } } inline constexpr T pop(){ if (sz_ == 0){cerr << "IndexError: pop from empty list" << endl; assert(false);} sz_--; return std::move(A[sz_]); } inline constexpr void reserve(uint new_sz){ if (new_sz > 2147483647){cerr << "ValueError: too large or negative size" << endl; assert(false);} if ((int)new_sz <= max_sz_){return;} max_sz_ = new_sz; auto B = new T[new_sz]{}; if (B == nullptr){cerr << "MemoryError: failed to reallocate memory" << endl; assert(false);} for (int i = 0; i < sz_; i++){B[i] = std::move(A[i]);} delete[] A; A = B; } inline constexpr void resize(uint new_sz, T elem = T()){ if (new_sz > 2147483647){cerr << "ValueError: too large or negative size" << endl; assert(false);} if ((int)new_sz <= max_sz_){ while (sz_ > (int)new_sz){pop();} for (int i = sz_, new_sz_int = new_sz; i < new_sz_int; i++){A[i] = elem;} sz_ = new_sz; return; } max_sz_ = new_sz + (new_sz >> 1); auto B = new T[max_sz_]{}; if (B == nullptr){cerr << "MemoryError: failed to reallocate memory" << endl; assert(false);} for (int i = 0; i < sz_; i++){B[i] = std::move(A[i]);} for (int i = sz_, new_sz_int = new_sz; i < new_sz_int; i++){B[i] = elem;} sz_ = new_sz; delete[] A; A = B; } template inline constexpr void assign(InputIterator first, InputIterator last){ reserve(last-first); while (first != last){append(*first); first++;} } inline constexpr void assign(uint n, const T& val){ reserve(n); sz_ = n; for (uint i = 0; i < n; i++){ A[i] = val; } } inline constexpr iterator insert(iterator pos, const T& val){ int idx = pos.check_idx(); append(val); for (int i = idx; i < sz_-1; i++){swap(A[i], A[sz_-1]);} return pos; } // inline constexpr void insert(iterator pos, iterator begin, iterator end) inline constexpr iterator erase(iterator pos){ int idx = pos.check_idx(); for (int i = idx; i < sz_-1; i++){ swap(A[i], A[i+1]); } A[sz_-1].~T(); sz_ -= 1; return pos; } inline constexpr iterator erase(iterator start, iterator end){ int startidx = start.check_idx_tolerate_end(), endidx = end.check_idx_tolerate_end(); if (startidx > endidx){cerr << "IndexError: invalid interval: [start, end) = []" << startidx << ", " << endidx << ")" << endl; assert(false);} for (int i = startidx; i < endidx; i++){ A[i].~T(); } if (startidx < endidx){ for (int i = endidx; i < sz_; i++){ swap(A[i+startidx-endidx], A[i]); } } sz_ -= endidx-startidx; return end; } inline constexpr void clear(){sz_ = 0; max_sz_ = 0; delete[] A; A = nullptr;} inline constexpr const T& operator[](int idx) const { check_and_adjust_idx(idx); return A[idx]; } inline constexpr T& operator[](int idx){ check_and_adjust_idx(idx); return A[idx]; } inline constexpr T& front(){return (*this)[0];} inline constexpr const T& front() const {return (*this)[0];} inline constexpr T& back(){return (*this)[-1];} inline constexpr const T& back() const {return (*this)[-1];} inline constexpr list operator[](int left, int right, int step = 1) const { if (step == 0){cerr << "ValueError: step argument must not be zero" << endl; assert(false);} if (step > 0){ int imax = left >= right ? 0 : (right-left+step-1)/step; list B(imax); for (int i = 0; i < imax; i++){ int target = left+step*i; if (target < 0 || target >= sz_){cerr << "IndexError: slice index out of range. current size: " << sz_ << " target index: " << target << endl; assert(false);} B[i] = A[target]; } return std::move(B); } else{ int imax = right >= left ? 0 : (left-right-step-1)/(-step); list B(imax); for (int i = 0; i < imax; i++){ int target = left+step*i; if (target < 0 || target >= sz_){cerr << "IndexError: slice index out of range. current size: " << sz_ << " target index: " << target << endl; assert(false);} B[i] = A[target]; } return std::move(B); } } inline constexpr T* data() {return empty() ? nullptr : &A[0];} inline constexpr const T* data() const {return empty() ? nullptr : &A[0];} inline constexpr T sum() const requires has_plus_operator && has_identity{ auto res = T(); for (int i = 0; i < sz_; i++){ res += A[i]; } return res; } template inline constexpr U sum(U init) const requires has_plus_operator{ for (int i = 0; i < sz_; i++){ init += A[i]; } return init; } inline constexpr void sort() requires has_compare_operator { std::sort(begin(), end()); } inline constexpr void sort_reverse() requires has_compare_operator { std::sort(begin(), end(), std::move([](const T& a, const T& b){return b < a;})); } inline constexpr void sort(const function& f){ std::sort(begin(), end(), f); } inline constexpr void reverse(){ std::reverse(begin(), end()); } inline constexpr ll count(const T& val){ ll res = 0; for (int i = 0; i < sz_; i++){res += A[i] == val;} return res; } inline constexpr ll index(const T& val){ for (int i = 0; i < sz_; i++){ if (A[i] == val){ return i; } } return -1; } inline constexpr ll rindex(const T& val){ for (int i = sz_-1; i >= 0; i--){ if (A[i] == val){ return i; } } return -1; } inline constexpr list allindex(const T& val){ list res; for (int i = 0; i < sz_; i++){ if (A[i] == val){ res.append(i); } } return res; } inline constexpr void apply(const function& f){for (int i = 0; i < sz_; i++){A[i] = f(A[i]);}} inline constexpr list> RLE(){ list> res; for (int l = 0, r = 0; l < sz_;){ while (r < sz_ && A[l] == A[r]){ r++; } res.append(make_pair(r-l, A[l])); l = r; } return res; } inline constexpr iterator lower_bound(const T& val) const requires has_compare_operator {return std::lower_bound(begin(), end(), val);} inline constexpr iterator upper_bound(const T& val) const requires has_compare_operator {return std::upper_bound(begin(), end(), val);} inline constexpr ll size() const {return sz_;} inline constexpr ll maxsize() const {return max_sz_;} inline constexpr bool empty() const {return sz_ == 0;} private: inline constexpr void check_and_adjust_idx(int& idx) const { if (idx >= sz_){cerr << "IndexError: index out of range. current size: " << sz_ << " target index: " << idx << endl; assert(false);} if (idx < 0){ if (idx < -sz_){cerr << "IndexError: index out of range. current size: " << sz_ << " target index: " << idx << endl; assert(false);} idx += sz_; } } int sz_; int max_sz_; T* A; }; #endif /* LIST__HPP_ */ #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; using lll = __int128_t; using ull = unsigned long long; #ifdef BOOST_VERSION using bll = boost::multiprecision::cpp_int; #endif using ld = long double; using pii = array; using pll = array; using plll = array; using tll = array; #define vall(A) A.begin(), A.end() template inline bool btest(T K, int i){return K&(1ull< inline constexpr ll len(const T& A){return ssize(A);} #endif constexpr ll pow2ll[63] = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304,8388608,16777216,33554432,67108864,134217728,268435456,536870912,1073741824,2147483648,4294967296,8589934592,17179869184,34359738368,68719476736,137438953472,274877906944,549755813888,1099511627776,2199023255552,4398046511104,8796093022208,17592186044416,35184372088832,70368744177664,140737488355328,281474976710656,562949953421312,1125899906842624,2251799813685248,4503599627370496,9007199254740992,18014398509481984,36028797018963968,72057594037927936,144115188075855872,288230376151711744,576460752303423488,1152921504606846976,2305843009213693952,4611686018427387904}; constexpr ll pow10ll[19] = {1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,10000000000,100000000000,1000000000000,10000000000000,100000000000000,1000000000000000,10000000000000000,100000000000000000,1000000000000000000}; constexpr ll di[4] = {0,1,0,-1}; constexpr ll di8[8] = {0,1,1,1,0,-1,-1,-1}; constexpr ll dj[4] = {1,0,-1,0}; constexpr ll dj8[8] = {1,1,0,-1,-1,-1,0,1}; #ifndef FASTIO__HPP_ #define FASTIO__HPP_ #include #include #include #include #include #include #include #include #include #include #include #include #include // C++20. Integer input must fit the destination type. For modint input, the // magnitude must fit uint64_t; negative values are reduced modulo the modulus. // FILE* is borrowed: it must outlive the reader/writer. Do not mix buffered // readers on one stream. The default input buffer is intended for batch judges; // interactive programs need BasicInput<1> and explicit output flush(). namespace fastio { namespace detail { template inline constexpr bool integer = std::is_integral_v; template struct unsigned_type { using type = std::make_unsigned_t; }; template<> struct unsigned_type { using type = unsigned char; }; #if defined(__SIZEOF_INT128__) template<> inline constexpr bool integer<__int128_t> = true; template<> inline constexpr bool integer<__uint128_t> = true; template<> struct unsigned_type<__int128_t> { using type = __uint128_t; }; template<> struct unsigned_type<__uint128_t> { using type = __uint128_t; }; #endif template using unsigned_t = typename unsigned_type::type; template inline constexpr bool signed_integer = integer && T(-1) < T(0); template concept modular = requires(T x) { x.val; } && (requires { T::mod_value; } || requires { T::mod(); }); template concept fraction = requires(T x) { x.denominator; }; template constexpr auto modulus() { if constexpr (requires { T::mod_value; }) return T::mod_value; else return T::mod(); } template concept indexed_range = requires(T& x) { std::size(x); x[0]; }; template concept tuple_like = requires { std::tuple_size::value; }; template inline constexpr bool unsupported = false; inline constexpr auto digit_pairs = [] { std::array result{}; for (int i = 0; i < 100; ++i) { result[2*i] = char('0'+i/10); result[2*i+1] = char('0'+i%10); } return result; }(); inline constexpr auto digit_quads = [] { std::array,10000> result{}; for (unsigned i = 0; i < 10000; ++i) { result[i] = {char('0'+i/1000),char('0'+i/100%10), char('0'+i/10%10),char('0'+i%10)}; } return result; }(); inline char* leading_quad(char* p, unsigned value) { if (value >= 1000) { std::memcpy(p,digit_quads[value].data(),4); return p+4; } if (value >= 100) { *p++ = char('0'+value/100); value %= 100; } else if (value < 10) { *p++ = char('0'+value); return p; } std::memcpy(p,digit_pairs.data()+2*value,2); return p+2; } inline char* decimal32(char* p, std::uint32_t value) { if (value >= 100000000) { p = leading_quad(p,value/100000000); value %= 100000000; std::memcpy(p,digit_quads[value/10000].data(),4); std::memcpy(p+4,digit_quads[value%10000].data(),4); return p+8; } if (value >= 10000) { p = leading_quad(p,value/10000); std::memcpy(p,digit_quads[value%10000].data(),4); return p+4; } return leading_quad(p,value); } template inline constexpr bool output32 = [] { if constexpr (integer) return sizeof(T) <= 4 && !std::is_same_v; else if constexpr (modular) return integer && sizeof(T{}.val) <= 4; else return false; }(); template inline char* decimal_small(char* p, const T& value) { if constexpr (modular) return decimal_small(p,value.val); else { std::uint32_t u = static_cast(value); if constexpr (signed_integer) { if (value < 0) { *p++ = '-'; u = 0-u; } } return decimal32(p,u); } } } // namespace detail template class BasicInput { static_assert(BufferSize > 0); std::FILE* file_; char buffer_[BufferSize+1]; std::size_t position_ = 0, size_ = 0; bool good_ = true; int peek() { if (position_ == size_) { size_ = std::fread(buffer_, 1, BufferSize, file_); buffer_[size_] = '\0'; position_ = 0; if (size_ == 0) return EOF; } return static_cast(buffer_[position_]); } int skip_space() { int c; while ((c = peek()) != EOF && c <= ' ') ++position_; return c; } template bool magnitude(U& value, bool& negative) { int c = skip_space(); if (c == EOF) return false; negative = c == '-'; if (c == '-' || c == '+') { ++position_; c = peek(); } if (static_cast(c-'0') > 9) return false; value = 0; do { const char* p = buffer_+position_; if constexpr (sizeof(U) >= 4 && std::endian::native == std::endian::little) { while (buffer_+size_-p >= 8) { std::uint64_t block; std::memcpy(&block,p,8); // All eight bytes must be ASCII decimal digits. if (((block+0x4646464646464646ULL) | (block-0x3030303030303030ULL)) & 0x8080808080808080ULL) break; block -= 0x3030303030303030ULL; block = (block*10+(block>>8)) & 0x00ff00ff00ff00ffULL; block = (block*100+(block>>16)) & 0x0000ffff0000ffffULL; block = (block*10000+(block>>32)) & 0xffffffffULL; value = value*100000000+static_cast(block); p += 8; if constexpr (SingleBlock || sizeof(U) == 4) break; } } unsigned digit; // The sentinel stops this loop without an EOF/buffer check for // every digit. Only a token crossing a refill needs the outer loop. while ((digit = static_cast(static_cast(*p)-'0')) <= 9) { value = value*10+digit; ++p; } position_ = static_cast(p-buffer_); if (position_ != size_) break; c = peek(); } while (static_cast(c-'0') <= 9); return true; } template bool read_one(T& value) { if constexpr (std::is_same_v) { const int c = skip_space(); if (c == EOF) return false; value = static_cast(c); ++position_; return true; } else if constexpr (detail::integer) { detail::unsigned_t u; bool negative; if (!magnitude(u,negative)) return false; if constexpr (detail::signed_integer) { // Never negate the minimum signed value, even for int128. value = negative && u != 0 ? -static_cast(u-1)-1 : static_cast(u); } else { if (negative || (std::is_same_v && u > 1)) return false; value = static_cast(u); } return true; } else if constexpr (detail::modular) { std::uint64_t u; bool negative; // Most modular coefficients have at most ten digits. After the // first eight, parse the short tail without another wide probe. if (!magnitude(u,negative)) return false; const auto mod = detail::modulus(); if (u >= mod) u %= mod; value.val = negative && u != 0 ? mod-u : u; return true; } else if constexpr (std::is_same_v) { int c = skip_space(); if (c == EOF) return false; value.clear(); do { value.push_back(static_cast(c)); ++position_; c = peek(); } while (c != EOF && c > ' '); return true; } else if constexpr (std::is_floating_point_v) { std::string token; if (!read_one(token)) return false; const char* first = token.data(); const char* last = first+token.size(); if (first != last && *first == '+') ++first; const auto result = std::from_chars(first,last,value); return result.ec == std::errc{} && result.ptr == last; } else if constexpr (detail::indexed_range) { const auto n = std::size(value); if constexpr (requires { std::data(value); }) { auto* data = std::data(value); for (decltype(std::size(value)) i = 0; i < n; ++i) if (!read_one(data[i])) return false; } else { for (decltype(std::size(value)) i = 0; i < n; ++i) if (!read_one(value[i])) return false; } return true; } else if constexpr (detail::tuple_like) { return std::apply([&](auto&... x) { return (read_one(x) && ...); },value); } else { static_assert(detail::unsupported, "Unsupported fastio input type"); } } public: explicit BasicInput(std::FILE* file = stdin) : file_(file) {} BasicInput(const BasicInput&) = delete; BasicInput& operator=(const BasicInput&) = delete; template bool read(T&... values) { if (!good_) return false; return good_ = (read_one(values) && ...); } template BasicInput& operator>>(T& value) { read(value); return *this; } explicit operator bool() const { return good_; } }; template class BasicOutput { static_assert(BufferSize > 0); std::FILE* file_; char buffer_[BufferSize]; std::size_t size_ = 0; bool good_ = true; bool drain() { if (!good_) return false; std::size_t done = 0; while (done < size_) { const auto n = std::fwrite(buffer_+done,1,size_-done,file_); if (n == 0) { size_ = 0; return good_ = false; } done += n; } size_ = 0; return true; } bool put(char c) { if (!good_ || (size_ == BufferSize && !drain())) return false; buffer_[size_++] = c; return true; } bool bytes(const char* data, std::size_t count) { if (!good_) return false; while (count != 0) { if (size_ == BufferSize && !drain()) return false; const auto room = BufferSize-size_; const auto n = count < room ? count : room; std::memcpy(buffer_+size_,data,n); size_ += n; data += n; count -= n; } return true; } template bool unsigned_number(U value, bool negative) { if constexpr (sizeof(U) <= 4 && BufferSize >= 12) { if (!good_ || (BufferSize-size_ < 12 && !drain())) return false; char* p = buffer_+size_; if (negative) *p++ = '-'; p = detail::decimal32(p,value); size_ = static_cast(p-buffer_); return true; } // 128-bit unsigned integers need at most 39 decimal digits. char digits[3*sizeof(U)+2]; char* const end = digits+sizeof(digits); char* p = end; while (value >= 100) { const U q = value/100; const unsigned r = static_cast(value-q*100); p -= 2; std::memcpy(p,detail::digit_pairs.data()+2*r,2); value = q; } if (value < 10) *--p = char('0'+static_cast(value)); else { p -= 2; std::memcpy(p,detail::digit_pairs.data()+2*static_cast(value),2); } if (negative) *--p = '-'; if constexpr (BufferSize >= sizeof(digits)) { if (!good_ || (BufferSize-size_ < sizeof(digits) && !drain())) return false; auto count = static_cast(end-p); char* dest = buffer_+size_; size_ += count; // Constant-size copies avoid a library call per integer. Each copy // stays inside the initialized digits and the reserved buffer area. if constexpr (sizeof(digits) >= 8) while (count >= 8) { std::memcpy(dest,p,8); dest += 8; p += 8; count -= 8; } if (count >= 4) { std::memcpy(dest,p,4); dest += 4; p += 4; count -= 4; } if (count >= 2) { std::memcpy(dest,p,2); dest += 2; p += 2; count -= 2; } if (count) *dest = *p; return true; } return bytes(p,static_cast(end-p)); } template bool write_one(const T& value) { if constexpr (std::is_same_v) { return put(value); } else if constexpr (detail::integer) { using U = detail::unsigned_t; U u = static_cast(value); bool negative = false; if constexpr (detail::signed_integer) { negative = value < 0; if (negative) u = U(0)-u; } return unsigned_number(u,negative); } else if constexpr (detail::modular) { return write_one(value.val); } else if constexpr (detail::fraction) { return write_one(value.numerator) && write_one("/") && write_one(value.denominator); } else if constexpr (std::is_convertible_v) { const std::string_view text(value); return bytes(text.data(),text.size()); } else if constexpr (std::is_floating_point_v) { char text[128]; const auto result = std::to_chars(text,text+sizeof(text),value); if (result.ec != std::errc{}) return false; return bytes(text,static_cast(result.ptr-text)); } else if constexpr (detail::indexed_range) { const auto n = std::size(value); using Element = std::remove_cvref_t; if constexpr (detail::indexed_range || detail::tuple_like){ for (decltype(std::size(value)) i = 0; i < n; ++i) { if (i != 0 && !put('\n')) return false; if (!write_one(value[i])) return false; } return true; } if constexpr (BufferSize >= 32 && detail::output32 && requires { std::data(value); }) { const auto* data = std::data(value); char* p = buffer_+size_; for (decltype(std::size(value)) i = 0; i < n; ++i) { if (buffer_+BufferSize-p < 12) { size_ = static_cast(p-buffer_); if (!drain()) return false; p = buffer_; } if (i != 0) *p++ = ' '; p = detail::decimal_small(p,data[i]); } size_ = static_cast(p-buffer_); return true; } for (decltype(std::size(value)) i = 0; i < n; ++i) { if (i != 0 && !put(' ')) return false; if (!write_one(value[i])) return false; } return true; } else if constexpr (detail::tuple_like) { [[maybe_unused]] bool first = true; return std::apply([&](const auto&... x) { return (((std::exchange(first,false) || put(' ')) && write_one(x)) && ...); },value); } else { static_assert(detail::unsupported, "Unsupported fastio output type"); } } public: explicit BasicOutput(std::FILE* file = stdout) : file_(file) {} BasicOutput(const BasicOutput&) = delete; BasicOutput& operator=(const BasicOutput&) = delete; ~BasicOutput() { flush(); } // write concatenates its arguments; print separates them with spaces and // appends a newline. Ranges and tuples use spaces between their elements. template bool write(const T&... values) { if (!good_) return false; return good_ = (write_one(values) && ...); } template bool print(const T&... values) { if (!good_) return false; [[maybe_unused]] bool first = true; good_ = (((std::exchange(first,false) || put(' ')) && write_one(values)) && ...); return good_ && put('\n'); } template bool printflush(const T&... values) { if (!good_) return false; [[maybe_unused]] bool first = true; good_ = (((std::exchange(first,false) || put(' ')) && write_one(values)) && ...); return good_ && put('\n') && flush(); } bool flush() { return drain() && (good_ = std::fflush(file_) == 0); } template BasicOutput& operator<<(const T& value) { write(value); return *this; } explicit operator bool() const { return good_; } }; #ifdef LOCAL_a1073741824 using FastInput = BasicInput<1>; #else using FastInput = BasicInput<>; #endif using FastOutput = BasicOutput<>; // template bool read(T&... values) { return in.read(values...); } // template bool write(const T&... values) { return out.write(values...); } // template bool print(const T&... values) { return out.print(values...); } // template bool printflush(const T&... values) { return out.print(values...) && out.flush(); } // inline bool flush() { return out.flush(); } } // namespace fastio #endif /* FASTIO__HPP_ */ fastio::FastInput in; fastio::FastOutput out; #define cin do_not_use_cin template bool read(T&... values) { return in.read(values...); } template bool write(const T&... values) { return out.write(values...); } template bool print(const T&... values) { return out.print(values...); } template bool printflush(const T&... values) { return out.print(values...) && out.flush(); } inline bool flush() { return out.flush(); } constexpr ll mod = 998244353; #ifndef PRIORITY__deque_HPP_ #define PRIORITY__deque_HPP_ #include #include #include using namespace std; /// @brief 両端優先度付きキュー /// @tparam T template struct priority_deque{ private: list A; void adjust_max_heap_from_bottom(int idx){ while (idx > 0){ if (A[((idx-1)>>1)&-2] < A[idx]){ swap(A[((idx-1)>>1)&-2], A[idx]); } else{return;} idx--; idx>>=1; idx&=-2; } } void adjust_min_heap_from_bottom(int idx){ while (idx > 1){ if (A[idx] < A[((idx-2)>>1)|1]){ swap(A[idx], A[((idx-2)>>1)|1]); } else{return;} idx-=2; idx>>=1; idx|=1; } } void build_heap(){ for (int i = A.size()-1; i >= 0; i--){ if ((i&1) && A[i-1] < A[i]){swap(A[i-1], A[i]);} int n = A.size(); int t = i; if (t&1){ while (2*t+1 < n){ int c = 2*t+3; if (n <= c || A[c-2] < A[c]) c -= 2; if (c < n && A[c] < A[t]){swap(A[t], A[c]); t = c;} else break; } } else { while (2*t+2 < n){ int c = 2*t+4; if (n <= c || A[c] < A[c-2]) c -= 2; if (c < n && A[t] < A[c]){swap(A[t], A[c]); t = c;} else break; } } if ((t|1) < (int)A.size() && A[t&-2] < A[t|1]){ swap(A[t&-2], A[t|1]); t ^= 1; } int p; while (i < t && A[p=(((t>>1)-1)&-2)] < A[t]){ swap(A[p], A[t]); t = p; } while (i < t && A[t] < A[p=(((t>>1)-1)|1)]){ swap(A[p], A[t]); t = p; } } } inline constexpr void assert_empty() const { if (A.empty()){ cerr << "IndexError: operation on an empty priority_deque" << endl; assert(false); } } public: priority_deque(const list& B){ A = B; build_heap(); } priority_deque(){} void push(const T& value){ if (A.size()&1){ if (A.back() < value){ A.insert(prev(A.end()), value); adjust_max_heap_from_bottom(A.size()-2); } else{ A.append(value); adjust_min_heap_from_bottom(A.size()-1); } } else{ A.append(value); if (A.size() == 1){return;} if (A[((A.size()-2)>>1)&-2] < A.back()){ adjust_max_heap_from_bottom(A.size()-1); } else if (A.back() < A[((A.size()-2)>>1)|1]){ swap(A.back(), A[((A.size()-2)>>1)|1]); adjust_min_heap_from_bottom(((A.size()-2)>>1)|1); } } } T pop_min(){ assert_empty(); if (A.size() == 1){T temp = std::move(A[0]); A.pop(); return temp;} T ret = std::move(A[1]); A[1] = A.back(); A.pop(); int idx = 1; while ((idx<<1)+1 < A.size()){ if ((idx<<1)+3 < A.size()){ if (A[idx] < A[(idx<<1)+1] && A[idx] < A[(idx<<1)+3]){ return ret; } if (A[(idx<<1)+1] < A[(idx<<1)+3]){ swap(A[idx], A[(idx<<1)+1]); idx<<=1; idx+=1; } else{ swap(A[idx], A[(idx<<1)+3]); idx<<=1; idx+=3; } } else{ if (A[(idx<<1)+1] < A[idx]){ swap(A[idx], A[(idx<<1)+1]); } idx<<=1; idx+=1; break; } } if (A.size() < 2){return ret;} if (A[idx-1] < A[idx]){ swap(A[idx], A[idx-1]); adjust_max_heap_from_bottom(idx-1); } return std::move(ret); } T pop_max(){ assert_empty(); T ret = std::move(A[0]); A[0] = A.back(); A.pop(); int idx = 0; while ((idx<<1)+2 < A.size()){ if ((idx<<1)+4 < A.size()){ if (A[(idx<<1)+2] < A[idx] && A[(idx<<1)+4] < A[idx]){ return ret; } if (A[(idx<<1)+2] < A[(idx<<1)+4]){ swap(A[idx], A[(idx<<1)+4]); idx<<=1; idx+=4; } else{ swap(A[idx], A[(idx<<1)+2]); idx<<=1; idx+=2; } } else{ if (A[idx] < A[(idx<<1)+2]){ swap(A[idx], A[(idx<<1)+2]); } idx<<=1; idx+=2; break; } } if (A.size() < 2){return ret;} if (idx+1 == A.size()){ if (A.back() < A[((idx-1)>>1)|1]){ swap(A.back(), A[((idx-1)>>1)|1]); adjust_min_heap_from_bottom(((idx-1)>>1)|1); } } else{ if (A[idx] < A[idx+1]){ swap(A[idx], A[idx+1]); adjust_min_heap_from_bottom(idx+1); } } return std::move(ret); } inline constexpr T get_min() const {assert_empty(); return A.size() > 1 ? A[1] : A[0];} inline constexpr T get_max() const {assert_empty(); return A[0];} inline constexpr bool empty() const {return A.empty();} inline constexpr ll size() const {return A.size();} }; #endif /* PRIORITY__deque_HPP_ */ void solve(){ ll N,M; in >> N >> M; list> E(N); for (ll i = 0; i < M; i++){ ll u,v,c; in >> u >> v >> c; u--; v--; E[u].append({v,c}); E[v].append({u,c}); } list greedy(N); //{dest , cost} for (int i = 0; i < N; i++){ ll mincost = pow2ll[60]; ll mincost_dest = -1; for (auto [w,c] : E[i]){ if (mincost > c){ mincost = c; mincost_dest = w; } } greedy[i] = {mincost_dest, mincost}; } list used(N, false); ll now = N-1; list> path; //{dist, now, dest} ll dist = 0; while (!used[now]){ used[now] = true; path.append({dist, now, greedy[now][0]}); dist += greedy[now][1]; now = greedy[now][0]; } used.assign(N, false); list D(N, -1); priority_deque pq; pq.push({0, 0}); while (!pq.empty()){ auto [d, n] = pq.pop_min(); if (used[n]){continue;} used[n] = true; D[n] = d; for (auto [w,c] : E[n]){ if (used[w]){continue;} pq.push({d+c, w}); } } ll shortest_path = D[N-1]; used.assign(N, false); list D2(N, -1); pq.push({0, N-1}); while (!pq.empty()){ auto [d, n] = pq.pop_min(); if (used[n]){continue;} used[n] = true; D2[n] = d; for (auto [w,c] : E[n]){ if (used[w]){continue;} pq.push({d+c, w}); } } for (ll i = 0; i < N; i++){ for (auto [w,c] : E[i]){ if (D[i] + c + D2[w] != shortest_path){continue;} ll dist2 = D[i]; ll u,v,r; if (path[-1][0] < dist2){ c = path[-1][0]-path[-2][0]; ll k = (dist2-path[-1][0])/c; if (k%2){ u = path[-1][2]; v = path[-1][1]; } else{ u = path[-1][1]; v = path[-1][2]; } r = dist2 - (path[-1][0]+k*c); } else{ auto itr = lower_bound(vall(path), array{dist2, pow2ll[60], pow2ll[60]}); --itr; u = (*itr)[1]; v = (*itr)[2]; r = dist2 - (*itr)[0]; } if (u == i && r == 0){print("Yes");return;} if (i == v && w == u){ print("Yes"); return; } dist2 = D[w]; if (path[-1][0] < dist2){ c = path[-1][0]-path[-2][0]; ll k = (dist2-path[-1][0])/c; if (k%2){ u = path[-1][2]; v = path[-1][1]; } else{ u = path[-1][1]; v = path[-1][2]; } r = dist2 - (path[-1][0]+k*c); } else{ auto itr = lower_bound(vall(path), array{dist2, pow2ll[60], pow2ll[60]}); --itr; u = (*itr)[1]; v = (*itr)[2]; r = dist2 - (*itr)[0]; } if (u == w && r == 0){print("Yes");return;} if (i == v && w == u){ print("Yes"); return; } } } print("No"); } int main(){ // ios::sync_with_stdio(false); // std::cin.tie(nullptr); ll T = 1; // in >> T; while (T--){ solve(); } }