結果

問題 No.2477 Drifting
ユーザー 👑 p-adicp-adic
提出日時 2023-09-17 22:30:18
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
RE  
実行時間 -
コード長 32,710 bytes
コンパイル時間 5,084 ms
コンパイル使用メモリ 262,232 KB
実行使用メモリ 247,356 KB
最終ジャッジ日時 2023-09-17 22:30:37
合計ジャッジ時間 16,964 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 RE -
testcase_01 AC 498 ms
47,228 KB
testcase_02 AC 790 ms
66,900 KB
testcase_03 AC 387 ms
25,756 KB
testcase_04 AC 197 ms
19,392 KB
testcase_05 AC 1,151 ms
71,604 KB
testcase_06 TLE -
testcase_07 -- -
testcase_08 -- -
testcase_09 -- -
testcase_10 -- -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

#ifdef DEBUG
  #define _GLIBCXX_DEBUG
  #define UNTIE ios_base::sync_with_stdio( false ); cin.tie( nullptr ); signal( SIGABRT , &AlertAbort )
  #define DEXPR( LL , BOUND , VALUE , DEBUG_VALUE ) CEXPR( LL , BOUND , DEBUG_VALUE )
  #define CERR( ... ) VariadicCout( cerr , __VA_ARGS__ ) << endl
  #define COUT( ... ) VariadicCout( cout << "出力: " , __VA_ARGS__ ) << endl
  #define CERR_A( A , N ) OUTPUT_ARRAY( cerr , A , N ) << endl
  #define COUT_A( A , N ) cout << "出力: "; OUTPUT_ARRAY( cout , A , N ) << endl
  #define CERR_ITR( A ) OUTPUT_ITR( cerr , A ) << endl
  #define COUT_ITR( A ) cout << "出力: "; OUTPUT_ITR( cout , A ) << endl
  #define ASSERT( A , MIN , MAX ) CERR( "ASSERTチェック: " , ( MIN ) , ( ( MIN ) <= A ? "<=" : ">" ) , A , ( A <= ( MAX ) ? "<=" : ">" ) , ( MAX ) ); assert( ( MIN ) <= A && A <= ( MAX ) )
  #define AUTO_CHECK bool auto_checked = true; AutoCheck( auto_checked ); if( auto_checked ){ return 0; };
#else
  #pragma GCC optimize ( "O3" )
  #pragma GCC optimize ( "unroll-loops" )
  #pragma GCC target ( "sse4.2,fma,avx2,popcnt,lzcnt,bmi2" )
  #define UNTIE ios_base::sync_with_stdio( false ); cin.tie( nullptr )
  #define DEXPR( LL , BOUND , VALUE , DEBUG_VALUE ) CEXPR( LL , BOUND , VALUE )
  #define CERR( ... ) 
  #define COUT( ... ) VariadicCout( cout , __VA_ARGS__ ) << "\n"
  #define CERR_A( A , N ) 
  #define COUT_A( A , N ) OUTPUT_ARRAY( cout , A , N ) << "\n"
  #define CERR_ITR( A ) 
  #define COUT_ITR( A ) OUTPUT_ITR( cout , A ) << "\n"
  #define ASSERT( A , MIN , MAX ) assert( ( MIN ) <= A && A <= ( MAX ) )
  #define AUTO_CHECK
#endif
#include <bits/stdc++.h>
using namespace std;
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using lld = __float128;
// #define RANDOM_TEST
#if defined( DEBUG ) && defined( RANDOM_TEST )
  ll GetRand( const ll& Rand_min , const ll& Rand_max );
 #define SET_ASSERT( A , MIN , MAX ) CERR( #A , " = " , ( A = GetRand( MIN , MAX ) ) )
 #define RETURN( ANSWER ) if( ( ANSWER ) == guchoku ){ CERR( ANSWER , "==" , guchoku ); goto END_MAIN; } else { CERR( ANSWER , "!=" , guchoku ); QUIT; }
#else
  #define SET_ASSERT( A , MIN , MAX ) cin >> A; ASSERT( A , MIN , MAX )
  #define RETURN( ANSWER ) COUT( ANSWER ); QUIT
#endif
#define ATT __attribute__( ( target( "sse4.2,fma,avx2,popcnt,lzcnt,bmi2" ) ) )
#define TYPE_OF( VAR ) decay_t<decltype( VAR )>
#define CEXPR( LL , BOUND , VALUE ) constexpr LL BOUND = VALUE
#define CIN( LL , ... ) LL __VA_ARGS__; VariadicCin( cin , __VA_ARGS__ )
#define CIN_ASSERT( A , MIN , MAX ) TYPE_OF( MAX ) A; SET_ASSERT( A , MIN , MAX )
#define CIN_A( LL , A , N ) LL A[N]; FOR( VARIABLE_FOR_CIN_A , 0 , N ){ cin >> A[VARIABLE_FOR_CIN_A]; }
#define GETLINE_SEPARATE( SEPARATOR , ... ) string __VA_ARGS__; VariadicGetline( cin , SEPARATOR , __VA_ARGS__ )
#define GETLINE( ... ) GETLINE_SEPARATE( " " , ... )
#define FOR( VAR , INITIAL , FINAL_PLUS_ONE ) for( TYPE_OF( FINAL_PLUS_ONE ) VAR = INITIAL ; VAR < FINAL_PLUS_ONE ; VAR ++ )
#define FOREQ( VAR , INITIAL , FINAL ) for( TYPE_OF( FINAL ) VAR = INITIAL ; VAR <= FINAL ; VAR ++ )
#define FOREQINV( VAR , INITIAL , FINAL ) for( TYPE_OF( INITIAL ) VAR = INITIAL ; VAR >= FINAL ; VAR -- )
#define AUTO_ITR( ARRAY ) auto itr_ ## ARRAY = ARRAY .begin() , end_ ## ARRAY = ARRAY .end()
#define FOR_ITR( ARRAY ) for( AUTO_ITR( ARRAY ) , itr = itr_ ## ARRAY ; itr_ ## ARRAY != end_ ## ARRAY ; itr_ ## ARRAY ++ , itr++ )
#define REPEAT( HOW_MANY_TIMES ) FOR( VARIABLE_FOR_REPEAT_ ## HOW_MANY_TIMES , 0 , HOW_MANY_TIMES )
#define SET_PRECISION( DECIMAL_DIGITS ) cout << fixed << setprecision( DECIMAL_DIGITS )
#define OUTPUT_ARRAY( OS , A , N ) FOR( VARIABLE_FOR_OUTPUT_ARRAY , 0 , N ){ OS << A[VARIABLE_FOR_OUTPUT_ARRAY] << (VARIABLE_FOR_OUTPUT_ARRAY==N-1?"":" "); } OS
#define OUTPUT_ITR( OS , A ) { auto ITERATOR_FOR_OUTPUT_ITR = A.begin() , END_FOR_OUTPUT_ITR = A.end(); bool VARIABLE_FOR_OUTPUT_ITR = ITERATOR_FOR_COUT_ITR != END_FOR_COUT_ITR; while( VARIABLE_FOR_OUTPUT_ITR ){ OS << *ITERATOR_FOR_COUT_ITR; ( VARIABLE_FOR_OUTPUT_ITR = ++ITERATOR_FOR_COUT_ITR != END_FOR_COUT_ITR ) ? OS : OS << " "; } } OS
#define QUIT goto END_MAIN
#define TEST_CASE_NUM( BOUND ) DEXPR( int , bound_T , BOUND , min( BOUND , 100 ) ); int T = 1; if constexpr( bound_T > 1 ){ SET_ASSERT( T , 1 , bound_T ); }
#define START_MAIN REPEAT( T ){ if constexpr( bound_T > 1 ){ CERR( "testcase " , VARIABLE_FOR_REPEAT_T , ":" ); }
#define START_WATCH chrono::system_clock::time_point watch = chrono::system_clock::now()
#define CURRENT_TIME static_cast<double>( chrono::duration_cast<chrono::microseconds>( chrono::system_clock::now() - watch ).count() / 1000.0 )
#define CHECK_WATCH( TL_MS ) ( CURRENT_TIME < TL_MS - 100.0 )
#define FINISH_MAIN END_MAIN: CERR( "" ); }

// 入出力用関数
template <class Traits> inline basic_istream<char,Traits>& VariadicCin( basic_istream<char,Traits>& is ) { return is; }
template <class Traits , typename Arg , typename... ARGS> inline basic_istream<char,Traits>& VariadicCin( basic_istream<char,Traits>& is , Arg& arg , ARGS&... args ) { return VariadicCin( is >> arg , args... ); }
template <class Traits> inline basic_istream<char,Traits>& VariadicGetline( basic_istream<char,Traits>& is , const char& separator ) { return is; }
template <class Traits , typename Arg , typename... ARGS> inline basic_istream<char,Traits>& VariadicGetline( basic_istream<char,Traits>& is , const char& separator , Arg& arg , ARGS&... args ) { return VariadicGetline( getline( is , arg , separator ) , separator , args... ); }
template <class Traits , typename Arg> inline basic_ostream<char,Traits>& VariadicCout( basic_ostream<char,Traits>& os , const Arg& arg ) { return os << arg; }
template <class Traits , typename Arg1 , typename Arg2 , typename... ARGS> inline basic_ostream<char,Traits>& VariadicCout( basic_ostream<char,Traits>& os , const Arg1& arg1 , const Arg2& arg2 , const ARGS&... args ) { return VariadicCout( os << arg1 << " " , arg2 , args... ); }

// 算術用関数
template <typename T> inline T Residue( const T& a , const T& p ){ return a >= 0 ? a % p : p - 1 - ( ( - ( a + 1 ) ) % p ); }
inline ll MIN( const ll& a , const ll& b ){ return min( a , b ); }
inline ull MIN( const ull& a , const ull& b ){ return min( a , b ); }
inline ll MAX( const ll& a , const ll& b ){ return max( a , b ); }
inline ull MAX( const ull& a , const ull& b ){ return max( a , b ); }

#define POWER( ANSWER , ARGUMENT , EXPONENT )				\
  static_assert( ! is_same<TYPE_OF( ARGUMENT ),int>::value && ! is_same<TYPE_OF( ARGUMENT ),uint>::value ); \
  TYPE_OF( ARGUMENT ) ANSWER{ 1 };					\
  {									\
    TYPE_OF( ARGUMENT ) ARGUMENT_FOR_SQUARE_FOR_POWER = ( ARGUMENT );	\
    TYPE_OF( EXPONENT ) EXPONENT_FOR_SQUARE_FOR_POWER = ( EXPONENT );	\
    while( EXPONENT_FOR_SQUARE_FOR_POWER != 0 ){			\
      if( EXPONENT_FOR_SQUARE_FOR_POWER % 2 == 1 ){			\
	ANSWER *= ARGUMENT_FOR_SQUARE_FOR_POWER;			\
      }									\
      ARGUMENT_FOR_SQUARE_FOR_POWER *= ARGUMENT_FOR_SQUARE_FOR_POWER;	\
      EXPONENT_FOR_SQUARE_FOR_POWER /= 2;				\
    }									\
  }									\

#define POWER_MOD( ANSWER , ARGUMENT , EXPONENT , MODULO )		\
  ll ANSWER{ 1 };							\
  {									\
    ll ARGUMENT_FOR_SQUARE_FOR_POWER = ( ( MODULO ) + ( ( ARGUMENT ) % ( MODULO ) ) ) % ( MODULO ); \
    TYPE_OF( EXPONENT ) EXPONENT_FOR_SQUARE_FOR_POWER = ( EXPONENT );	\
    while( EXPONENT_FOR_SQUARE_FOR_POWER != 0 ){			\
      if( EXPONENT_FOR_SQUARE_FOR_POWER % 2 == 1 ){			\
	ANSWER = ( ANSWER * ARGUMENT_FOR_SQUARE_FOR_POWER ) % ( MODULO ); \
      }									\
      ARGUMENT_FOR_SQUARE_FOR_POWER = ( ARGUMENT_FOR_SQUARE_FOR_POWER * ARGUMENT_FOR_SQUARE_FOR_POWER ) % ( MODULO ); \
      EXPONENT_FOR_SQUARE_FOR_POWER /= 2;				\
    }									\
  }									\

#define FACTORIAL_MOD( ANSWER , ANSWER_INV , INVERSE , MAX_INDEX , CONSTEXPR_LENGTH , MODULO ) \
  static ll ANSWER[CONSTEXPR_LENGTH];					\
  static ll ANSWER_INV[CONSTEXPR_LENGTH];				\
  static ll INVERSE[CONSTEXPR_LENGTH];					\
  {									\
    ll VARIABLE_FOR_PRODUCT_FOR_FACTORIAL = 1;				\
    ANSWER[0] = VARIABLE_FOR_PRODUCT_FOR_FACTORIAL;			\
    FOREQ( i , 1 , MAX_INDEX ){						\
      ANSWER[i] = ( VARIABLE_FOR_PRODUCT_FOR_FACTORIAL *= i ) %= ( MODULO ); \
    }									\
    ANSWER_INV[0] = ANSWER_INV[1] = INVERSE[1] = VARIABLE_FOR_PRODUCT_FOR_FACTORIAL = 1; \
    FOREQ( i , 2 , MAX_INDEX ){						\
      ANSWER_INV[i] = ( VARIABLE_FOR_PRODUCT_FOR_FACTORIAL *= INVERSE[i] = ( MODULO ) - ( ( ( ( MODULO ) / i ) * INVERSE[ ( MODULO ) % i ] ) % ( MODULO ) ) ) %= ( MODULO ); \
    }									\
  }									\

// 二分探索テンプレート
// EXPRESSIONがANSWERの広義単調関数の時、EXPRESSION >= TARGETの整数解を格納。
#define BS( ANSWER , MINIMUM , MAXIMUM , EXPRESSION , DESIRED_INEQUALITY , TARGET , INEQUALITY_FOR_CHECK , UPDATE_U , UPDATE_L , UPDATE_ANSWER ) \
  static_assert( ! is_same<TYPE_OF( TARGET ),uint>::value && ! is_same<TYPE_OF( TARGET ),ull>::value ); \
  ll ANSWER = MINIMUM;							\
  if( MINIMUM <= MAXIMUM ){						\
    ll VARIABLE_FOR_BINARY_SEARCH_L = MINIMUM;				\
    ll VARIABLE_FOR_BINARY_SEARCH_U = MAXIMUM;				\
    ANSWER = ( VARIABLE_FOR_BINARY_SEARCH_L + VARIABLE_FOR_BINARY_SEARCH_U ) / 2; \
    ll VARIABLE_FOR_DIFFERENCE_FOR_BINARY_SEARCH;			\
    while( VARIABLE_FOR_BINARY_SEARCH_L != VARIABLE_FOR_BINARY_SEARCH_U ){ \
      VARIABLE_FOR_DIFFERENCE_FOR_BINARY_SEARCH = ( EXPRESSION ) - ( TARGET ); \
      CERR( "二分探索中: " << VARIABLE_FOR_BINARY_SEARCH_L << "<=" << ANSWER << "<=" << VARIABLE_FOR_BINARY_SEARCH_U << ":" << EXPRESSION << "-" << TARGET << "=" << VARIABLE_FOR_DIFFERENCE_FOR_BINARY_SEARCH ); \
      if( VARIABLE_FOR_DIFFERENCE_FOR_BINARY_SEARCH INEQUALITY_FOR_CHECK 0 ){	\
	VARIABLE_FOR_BINARY_SEARCH_U = UPDATE_U;			\
      } else {								\
	VARIABLE_FOR_BINARY_SEARCH_L = UPDATE_L;			\
      }									\
      ANSWER = UPDATE_ANSWER;						\
    }									\
    CERR( "二分探索終了: " << VARIABLE_FOR_BINARY_SEARCH_L << "<=" << ANSWER << "<=" << VARIABLE_FOR_BINARY_SEARCH_U << ":" << EXPRESSION << ( EXPRESSION > TARGET ? ">" : EXPRESSION < TARGET ? "<" : "=" ) << TARGET ); \
    CERR( ( EXPRESSION DESIRED_INEQUALITY TARGET ? "二分探索成功" : "二分探索失敗" ) ); \
    assert( EXPRESSION DESIRED_INEQUALITY TARGET );			\
  } else {								\
    CERR( "二分探索失敗: " << MINIMUM << ">" << MAXIMUM );		\
    assert( MINIMUM <= MAXIMUM );					\
  }									\

// 単調増加の時にEXPRESSION >= TARGETの最小解を格納。
#define BS1( ANSWER , MINIMUM , MAXIMUM , EXPRESSION , TARGET )		\
  BS( ANSWER , MINIMUM , MAXIMUM , EXPRESSION , >= , TARGET , >= , ANSWER , ANSWER + 1 , ( VARIABLE_FOR_BINARY_SEARCH_L + VARIABLE_FOR_BINARY_SEARCH_U ) / 2 ) \

// 単調増加の時にEXPRESSION <= TARGETの最大解を格納。
#define BS2( ANSWER , MINIMUM , MAXIMUM , EXPRESSION , TARGET )		\
  BS( ANSWER , MINIMUM , MAXIMUM , EXPRESSION , <= , TARGET , > , ANSWER - 1 , ANSWER , ( VARIABLE_FOR_BINARY_SEARCH_L + 1 + VARIABLE_FOR_BINARY_SEARCH_U ) / 2 ) \

// 単調減少の時にEXPRESSION >= TARGETの最大解を格納。
#define BS3( ANSWER , MINIMUM , MAXIMUM , EXPRESSION , TARGET )		\
  BS( ANSWER , MINIMUM , MAXIMUM , EXPRESSION , >= , TARGET , < , ANSWER - 1 , ANSWER , ( VARIABLE_FOR_BINARY_SEARCH_L + 1 + VARIABLE_FOR_BINARY_SEARCH_U ) / 2 ) \

// 単調減少の時にEXPRESSION <= TARGETの最小解を格納。
#define BS4( ANSWER , MINIMUM , MAXIMUM , EXPRESSION , TARGET )		\
  BS( ANSWER , MINIMUM , MAXIMUM , EXPRESSION , <= , TARGET , <= , ANSWER , ANSWER + 1 , ( VARIABLE_FOR_BINARY_SEARCH_L + VARIABLE_FOR_BINARY_SEARCH_U ) / 2 ) \

// t以下の値が存在すればその最大値のiterator、存在しなければend()を返す。
template <typename T> inline typename set<T>::iterator MaximumLeq( set<T>& S , const T& t ) { const auto end = S.end(); if( S.empty() ){ return end; } auto itr = S.upper_bound( t ); return itr == end ? S.find( *( S.rbegin() ) ) : itr == S.begin() ? end : --itr; }
// t未満の値が存在すればその最大値のiterator、存在しなければend()を返す。
template <typename T> inline typename set<T>::iterator MaximumLt( set<T>& S , const T& t ) { const auto end = S.end(); if( S.empty() ){ return end; } auto itr = S.lower_bound( t ); return itr == end ? S.find( *( S.rbegin() ) ) : itr == S.begin() ? end : --itr; }
// t以上の値が存在すればその最小値のiterator、存在しなければend()を返す。
template <typename T> inline typename set<T>::iterator MinimumGeq( set<T>& S , const T& t ) { return S.lower_bound( t ); }
// tより大きい値が存在すればその最小値のiterator、存在しなければend()を返す。
template <typename T> inline typename set<T>::iterator MinimumGt( set<T>& S , const T& t ) { return S.upper_bound( t ); }

// データ構造用関数
template <typename T> inline T add( const T& t0 , const T& t1 ) { return t0 + t1; }
template <typename T> inline T xor_add( const T& t0 , const T& t1 ){ return t0 ^ t1; }
template <typename T> inline T multiply( const T& t0 , const T& t1 ) { return t0 * t1; }
template <typename T> inline const T& zero() { static const T z = 0; return z; }
template <typename T> inline const T& one() { static const T o = 1; return o; }\
template <typename T> inline T add_inv( const T& t ) { return -t; }
template <typename T> inline T id( const T& v ) { return v; }

// グリッド問題用関数
int H , W , H_minus , W_minus , HW;
inline pair<int,int> EnumHW( const int& v ) { return { v / W , v % W }; }
inline int EnumHW_inv( const int& h , const int& w ) { return h * W + w; }
const string direction[4] = {"U","R","D","L"};
// (i,j)->(k,h)の方向番号を取得
inline int DirectionNumberOnGrid( const int& i , const int& j , const int& k , const int& h ){return i<k?2:i>k?0:j<h?1:j>h?3:(assert(false),-1);}
// v->wの方向番号を取得
inline int DirectionNumberOnGrid( const int& v , const int& w ){auto [i,j]=EnumHW(v);auto [k,h]=EnumHW(w);return DirectionNumberOnGrid(i,j,k,h);}
// 方向番号の反転U<->D、R<->L
inline int ReverseDirectionNumberOnGrid( const int& n ){assert(0<=n&&n<4);return(n+2)%4;}

// デバッグ用関数
#ifdef DEBUG
  inline void AlertAbort( int n ) { CERR( "abort関数が呼ばれました。assertマクロのメッセージが出力されていない場合はオーバーフローの有無を確認をしてください。" ); }
  void AutoCheck( bool& auto_checked );
#endif

// 圧縮用
#define TE template
#define TY typename
#define US using
#define ST static
#define IN inline
#define CL class
#define PU public
#define OP operator
#define CE constexpr
#define CO const
#define NE noexcept
#define RE return 
#define WH while
#define VO void
#define VE vector
#define LI list
#define BE begin
#define EN end
#define SZ size
#define MO move
#define TH this
#define CRI CO int&
#define CRUI CO uint&
#define CRL CO ll&

// VVV ライブラリは以下に挿入する。

#define DIJKSTRA_BODY( INITIALISE_PREV , SET_PREV )			\
  static const U& unit = Unit();					\
  assert( unit != m_found && unit < m_infty );				\
  U weight[size_max];							\
									\
  for( int i = 0 ; i < m_size ; i++ ){					\
									\
    weight[i] = m_infty;						\
									\
  }									\
									\
  set<pair<U,int> > vertex{};						\
  const int i_start = e_inv( t_start );					\
  const int i_final = e_inv( t_final );					\
  vertex.insert( pair<U,int>( weight[i_start] = unit , i_start ) );	\
  INITIALISE_PREV;							\
									\
  if( i_start != i_final ){						\
									\
    while( ! vertex.empty() ){						\
									\
      auto itr_vertex = vertex.begin();					\
      const pair<U,int> v = *itr_vertex;				\
      const int& i = v.second;						\
									\
      if( i == i_final ){						\
									\
	break;								\
									\
      }									\
									\
      const U& u = v.first;						\
      weight[i] = m_found;						\
      vertex.erase( itr_vertex );					\
      const list<pair<T,U> > edge_i = E( e( i ) );			\
      list<pair<U,int> > changed_vertex{};				\
									\
      for( auto itr_edge_i = edge_i.begin() , end_edge_i = edge_i.end() ; itr_edge_i != end_edge_i ; itr_edge_i++ ){ \
									\
	const int& j = e_inv( itr_edge_i->first );			\
	U& weight_j = weight[j];					\
									\
	if( weight_j != m_found ){					\
									\
	  const U& edge_ij = itr_edge_i->second;			\
	  const U temp = Addition( u , edge_ij );			\
	  assert( edge_ij != m_found && temp != m_found && !( temp < edge_ij ) && temp < m_infty ); \
									\
	  if( weight_j > temp ){					\
									\
	    if( weight_j != m_infty ){					\
									\
	      vertex.erase( pair<U,int>( weight_j , j ) );		\
									\
	    }								\
									\
	    SET_PREV;							\
	    changed_vertex.push_back( pair<U,int>( weight_j = temp , j ) ); \
									\
	  }								\
									\
	}								\
									\
      }									\
									\
      for( auto itr_changed = changed_vertex.begin() , end_changed = changed_vertex.end() ; itr_changed != end_changed ; itr_changed++ ){ \
									\
	vertex.insert( *itr_changed );					\
									\
      }									\
									\
    }									\
									\
  }									\


// メモリが不足する場合はEの定義を前計算しないでその都度計算させること。
template <typename T , typename U , list<pair<T,U> > E(const T&) , int size_max>
class DijkstraBody
{

private:
  int m_size;
  U m_infty;
  U m_found;

  int m_length;
  map<T,int> m_memory;
  vector<T> m_memory_inv;
  
public:
  inline DijkstraBody( const int& size , const U& infty , const U& found );
  // 経路が存在しない場合の返り値はm_infty
  U Solve( const T& t_start , const T& t_final );
  U Solve( const T& t_start , const T& t_final , list<T>& path );

  const U& Infty() const;
  
private:
  virtual const U& Unit() const = 0;
  virtual U Addition( const U& , const U& ) const = 0;
  virtual T e( const int& i );
  virtual int e_inv( const T& t );
  virtual void Reset();

};

// 入力の範囲内で要件
// (1) Eの値の各成分の第2成分が0以上である。
// (2) 2^{31}-1がEの値の各成分の第2成分size_max個以下の和で表せるいかなる数よりも大きい。
// (6) Vの各要素u,vに対し、辺u->vが複数存在する場合は重みが最小のものが前にpushされている。
// が成り立つ場合にのみサポート。

// O((size+|E|)log size)で単一始点最短経路探索。
template <list<pair<int,ll> > E(const int&) , int size_max>
class Dijkstra :
  public DijkstraBody<int,ll,E,size_max>
{

public:
  inline Dijkstra( const int& size );
  
private:
  inline const ll& Unit() const;
  inline ll Addition( const ll& , const ll& ) const;
  inline int e( const int& i );
  inline int e_inv( const int& t );
  inline void Reset();

};

// 入力の範囲内で要件
// (1) Eの値の各成分の第2成分がe_T()以上である。
// (2) inftyがEの値の各成分の第2成分size_max個以下の和で表せるいかなる項よりも大きい。
// (3) foundがEの値の各成分の第2成分size_max個以下の和で表せず、inftyとも異なる。
// (4) (U,m_U:U^2->U,e_U:1->U)がbool operator<(const U&,const U&)に関して順序モノイドである。
// (6) Vの各要素u,vに対し、辺u->vが複数存在する場合は重みが最小のものが前にpushされている。
// が成り立つ場合にのみサポート。

// O((size+|E|)(log size)^2)で単一始点最短経路探索。
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max>
class MemorisationDijkstra :
  public DijkstraBody<T,U,E,size_max>
{

public:
  inline MemorisationDijkstra( const int& size , const U& infty = 9223372036854775807 , const U& found = -1 );
  
private:
  inline const U& Unit() const;
  inline U Addition( const U& , const U& ) const;

};

// 入力の範囲内で要件
// (1) Eの値の各成分の第2成分がe_T()以上である。
// (2) inftyがEの値の各成分の第2成分size_max個以下の和で表せるいかなる項よりも大きい。
// (3) foundがEの値の各成分の第2成分size_max個以下の和で表せず、inftyとも異なる。
// (4) (U,m_U:U^2->U,e_U:1->U)がbool operator<(const U&,const U&)に関して順序モノイドである。
// (5) (enum_T,enum_T_inv)が互いに逆写像である。
// (6) Vの各要素u,vに対し、辺u->vが複数存在する場合は重みが最小のものが前にpushされている。
// が成り立つ場合にのみサポート。

// O((size+|E|)log size)で単一始点最短経路探索。
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max , T enum_T(const int&) , int enum_T_inv(const T&)>
class EnumerationDijkstra :
  public DijkstraBody<T,U,E,size_max>
{

public:
  inline EnumerationDijkstra( const int& size , const U& infty = 9223372036854775807 , const U& found = -1 );
  
private:
  inline const U& Unit() const;
  inline U Addition( const U& , const U& ) const;
  inline T e( const int& i );
  inline int e_inv( const T& t );
  inline void Reset();

};


template <typename T , typename U , list<pair<T,U> > E(const T&) , int size_max> inline DijkstraBody<T,U,E,size_max>::DijkstraBody( const int& size , const U& infty , const U& found ) : m_size( size ) , m_infty( infty ) , m_found( found ) , m_length() , m_memory() , m_memory_inv() { static_assert( ! is_same<U,int>::value ); }
template <list<pair<int,ll> > E(const int&) , int size_max> inline Dijkstra<E,size_max>::Dijkstra( const int& size ) : DijkstraBody<int,ll,E,size_max>( size , 9223372036854775807 , -1 ) {}
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max> inline MemorisationDijkstra<T,U,m_U,e_U,E,size_max>::MemorisationDijkstra( const int& size , const U& infty , const U& found ) : DijkstraBody<T,U,E,size_max>( size , infty , found ) {}
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max , T enum_T(const int&) , int enum_T_inv(const T&)> inline EnumerationDijkstra<T,U,m_U,e_U,E,size_max,enum_T,enum_T_inv>::EnumerationDijkstra( const int& size , const U& infty , const U& found ) : DijkstraBody<T,U,E,size_max>( size , infty , found ) {}

template <typename T , typename U , list<pair<T,U> > E(const T&) , int size_max>
U DijkstraBody<T,U,E,size_max>::Solve( const T& t_start , const T& t_final )
{

  DIJKSTRA_BODY( , );
  Reset();
  return weight[i_final];

}

template <typename T , typename U , list<pair<T,U> > E(const T&) , int size_max>
U DijkstraBody<T,U,E,size_max>::Solve( const T& t_start , const T& t_final , list<T>& path )
{

  DIJKSTRA_BODY( T prev[size_max] = {} , prev[j] = i );
  int i = i_final;

  while( i != i_start ){

    path.push_front( e( i ) );
    i = prev[i];

  }

  path.push_front( t_start );
  Reset();
  return weight[i_final];

}

template <typename T , typename U , list<pair<T,U> > E(const T&) , int size_max> const U& DijkstraBody<T,U,E,size_max>::Infty() const { return m_infty; }

template <list<pair<int,ll> > E(const int&) , int size_max> inline const ll& Dijkstra<E,size_max>::Unit() const { static const ll unit = 0; return unit; }
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max> inline const U& MemorisationDijkstra<T,U,m_U,e_U,E,size_max>::Unit() const { return e_U(); }
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max , T enum_T(const int&) , int enum_T_inv(const T&)> inline const U& EnumerationDijkstra<T,U,m_U,e_U,E,size_max,enum_T,enum_T_inv>::Unit() const { return e_U(); }

template <list<pair<int,ll> > E(const int&) , int size_max> inline ll Dijkstra<E,size_max>::Addition( const ll& u0 , const ll& u1 ) const { return u0 + u1; }
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max> inline U MemorisationDijkstra<T,U,m_U,e_U,E,size_max>::Addition( const U& u0 , const U& u1 ) const { return m_U( u0 , u1 ); }
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max , T enum_T(const int&) , int enum_T_inv(const T&)> inline U EnumerationDijkstra<T,U,m_U,e_U,E,size_max,enum_T,enum_T_inv>::Addition( const U& u0 , const U& u1 ) const { return m_U( u0 , u1 ); }

template <typename T , typename U , list<pair<T,U> > E(const T&) , int size_max>
T DijkstraBody<T,U,E,size_max>::e( const int& i )
{
  
  assert( i < m_length );
  return m_memory_inv[i];

}

template <list<pair<int,ll> > E(const int&) , int size_max> inline int Dijkstra<E,size_max>::e( const int& i ) { return i; }
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max , T enum_T(const int&) , int enum_T_inv(const T&)> inline T EnumerationDijkstra<T,U,m_U,e_U,E,size_max,enum_T,enum_T_inv>::e( const int& i ) { return enum_T( i ); }

template <typename T , typename U , list<pair<T,U> > E(const T&) , int size_max>
int DijkstraBody<T,U,E,size_max>::e_inv( const T& t )
{

  if( m_memory.count( t ) == 0 ){

    assert( m_length < m_size );
    m_memory_inv.push_back( t );
    return m_memory[t] = m_length++;

  }
  
  return m_memory[t];

}

template <list<pair<int,ll> > E(const int&) , int size_max> inline int Dijkstra<E,size_max>::e_inv( const int& t ) { return t; }
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max , T enum_T(const int&) , int enum_T_inv(const T&)> inline int EnumerationDijkstra<T,U,m_U,e_U,E,size_max,enum_T,enum_T_inv>::e_inv( const T& t ) { return enum_T_inv( t ); }

template <typename T , typename U , list<pair<T,U> > E(const T&) , int size_max>
void DijkstraBody<T,U,E,size_max>::Reset()
{

  m_length = 0;
  m_memory.clear();
  m_memory_inv.clear();
  return;

}

template <list<pair<int,ll> > E(const int&) , int size_max> inline void Dijkstra<E,size_max>::Reset() {}
template <typename T , typename U , U m_U(const U&,const U&) , const U& e_U() , list<pair<T,U> > E(const T&) , int size_max , T enum_T(const int&) , int enum_T_inv(const T&)> inline void EnumerationDijkstra<T,U,m_U,e_U,E,size_max,enum_T,enum_T_inv>::Reset() {}

// AAA ライブラリは以上に挿入する。

// データ構造使用畤のNの上限
// inline CEXPR( int , bound_N , 10 );
inline DEXPR( int , bound_N , 100000 , 100 ); // 0が5個
// inline CEXPR( int , bound_N , 1000000000 ); // 0が9個
// inline CEXPR( ll , bound_N , 1000000000000000000 ); // 0が18個

// データ構造使用畤のMの上限
// inline CEXPR( TYPE_OF( bound_N ) , bound_M , bound_N );
// inline CEXPR( int , bound_M , 10 );
inline DEXPR( int , bound_M , 200000 , 100 ); // 0が5個
// inline CEXPR( int , bound_M , 1000000000 ); // 0が9個
// inline CEXPR( ll , bound_M , 1000000000000000000 ); // 0が18個

// データ構造や壁配列使用畤のH,Wの上限
inline DEXPR( int , bound_H , 1000 , 20 );
// inline DEXPR( int , bound_H , 100000 , 10 ); // 0が5個
// inline CEXPR( int , bound_H , 1000000000 ); // 0が9個
inline CEXPR( int , bound_W , bound_H );
static_assert( ll( bound_H ) * bound_W < ll( 1 ) << 31 );
inline CEXPR( int , bound_HW , bound_H * bound_W );
// CEXPR( int , bound_HW , 100000 ); // 0が5個
// CEXPR( int , bound_HW , 1000000 ); // 0が6個
inline void SetEdgeOnGrid( const string& Si , const int& i , list<int> ( &e )[bound_HW] , const char& walkable = '.' ){FOR(j,0,W){if(Si[j]==walkable){int v = EnumHW_inv(i,j);if(i>0){e[EnumHW_inv(i-1,j)].push_back(v);}if(i+1<H){e[EnumHW_inv(i+1,j)].push_back(v);}if(j>0){e[EnumHW_inv(i,j-1)].push_back(v);}if(j+1<W){e[EnumHW_inv(i,j+1)].push_back(v);}}}}
inline void SetEdgeOnGrid( const string& Si , const int& i , list<pair<int,ll> > ( &e )[bound_HW] , const char& walkable = '.'  , const char& unwalkable = '#' ){FOR(j,0,W){if(Si[j]==walkable){const int v=EnumHW_inv(i,j);if(i>0){e[EnumHW_inv(i-1,j)].push_back({v,1});}if(i+1<H){e[EnumHW_inv(i+1,j)].push_back({v,1});}if(j>0){e[EnumHW_inv(i,j-1)].push_back({v,1});}if(j+1<W){e[EnumHW_inv(i,j+1)].push_back({v,1});}}}}
inline void SetWallOnGrid( const string& Si , const int& i , bool ( &non_wall )[bound_H+1][bound_W+1] , const char& walkable = '.'  , const char& unwalkable = '#' ){bool(&non_wall_i)[bound_W+1]=non_wall[i];FOR(j,0,W){non_wall_i[j]=Si[j]==walkable?true:(assert(Si[j]==unwalkable),false);}}

// using path_type = int;
using path_type = pair<int,ll>;
CEXPR( int , bound_E , bound_M ); // bound_Mのデフォルト値は10^5。
// CEXPR( int , bound_E , bound_HW ); // bound_HWのデフォルト値は10^6。
list<path_type> e[bound_E] = {};
list<path_type> E( const int& i )
{
  // list<path_type> answer{};
  list<path_type> answer = e[i];
  // 入力によらない処理
  return answer;
}

// ライブラリをここに挿入しない。

int main()
{
  UNTIE;
  AUTO_CHECK;
  // START_WATCH;
  TEST_CASE_NUM( 1 );
  START_MAIN;

  // CEXPR( ll , P , 998244353 );
  // // CEXPR( ll , P , 1000000007 ); // Mod<P>を使う時はP2に変更。

  CIN( ll , N );
  CIN( ll , M );
  // CIN( ll , N , M , K );
  // // CIN_ASSERT( N , 1 , bound_N ); // 基本不要。上限のデフォルト値は10^5。
  // // CIN_ASSERT( M , 1 , bound_M ); // 基本不要。上限のデフォルト値は10^5。

  // CIN( string , S );
  // CIN( string , T );
  
  // CIN_A( ll , A , N );
  // // CIN_A( ll , B , N );
  // // ll A[N];
  // // ll B[N];
  // // ll A[bound_N]; // 関数(コンストラクタ)の引数に使う。長さのデフォルト値は10^5。
  // // ll B[bound_N]; // 関数(コンストラクタ)の引数に使う。長さのデフォルト値は10^5。
  // // FOR( i , 0 , N ){
  // //   cin >> A[i] >> B[i];
  // // }

  map<pair<int,int>,pair<int,int> > v{};
  int size = 0;
  set<int> to[N+2];
  v[{0,1}] = { size++ , 0 };
  to[1].insert( 0 );
  v[{N,N+1}] = { size++ , 0 };
  to[N+1].insert( N );
  FOR( j , 0 , M ){
    CIN( int , x , y , w );
    to[y].insert( x );
    v[{ x , y }] = { size++ , w };
  }
  set<pair<int,ll> > e_set[M+2]{};
  FOR_ITR( v ){
    auto key = itr->first;
    auto& [x,y] = key;
    auto& [i,w] = itr->second;
    auto& tox = to[x];
    FOR_ITR( tox ){
      e_set[v[{*itr,x}].first].insert( { i , w } );
    }
  }
  
  CIN( ll , K );
  FOR( j , 0 , K ){
    CIN( int , x , y , z );
    if( v.count( {x,y} ) != 0 && v.count( {y,z} ) != 0 ){
      auto& [i,w] = v[{y,z}];
      e_set[v[{x,y}].first].erase( { i , w } );
    }
  }
  FOR( i , 0 , size ){
    auto& e_set_i = e_set[i];
    FOR_ITR( e_set_i ){
      e[i].push_back( *itr );
    }
    e_set_i.clear();
  }

  Dijkstra<E,bound_M+2> d( M + 2 );
  // CIN( int , Q );
  // // DEXPR( int , bound_Q , 100000 , 100 ); // 基本不要。
  // // CIN_ASSERT( Q , 1 , bound_Q ); // 基本不要。
  // tuple<int,int,int> query[Q];
  // FOR( q , 0 , Q ){
  //   CIN( int , type );
  //   if( type == 1 ){
  //     CIN( int , x , y );
  //     // query[q] = { type , x , y };
  //   } else if( type == 2 ){
  //     CIN( int , x , y );
  //     // query[q] = { type , x , y };
  //   } else {
  //     CIN( int , x , y );
  //     // query[q] = { type , x , y };
  //   }
  // }
  
  // cin >> H >> W;
  // // SET_ASSERT( H , 1 , bound_H ); // 基本不要。上限のデフォルト値は10^3。
  // // SET_ASSERT( W , 1 , bound_W ); // 基本不要。上限のデフォルト値は10^3。
  // H_minus = H - 1;
  // W_minus = W - 1;
  // HW = H * W;
  // // assert( HW <= bound_HW ); // 基本不要。上限のデフォルト値は10^6。
  // string S[H];
  // // bool non_wall[bound_H+1][bound_W+1]={};
  // FOR( i , 0 , H ){
  //   cin >> S[i];
  //   // SetEdgeOnGrid( S[i] , i , e ); // bound_Eの定義変更が必要。
  //   // SetWallOnGrid( S[i] , i , non_wall );
  // }
  // // {h,w}へデコード: EnumHW( v )
  // // {h,w}をコード: EnumHW_inv( h , w );
  // // (i,j)->(k,h)の方向番号を取得: DirectionNumberOnGrid( i , j , k , h );
  // // v->wの方向番号を取得: DirectionNumberOnGrid( v , w );
  // // 方向番号の反転U<->D、R<->L: ReverseDirectionNumberOnGrid( n );

  // while( CHECK_WATCH( 2000.0 ) ){

  // }

  // // ll guchoku = Guchoku();
  ll answer = d.Solve( v[{0,1}].first , v[{N,N+1}].first );
  answer == d.Infty() ? answer = -1 : answer;
  // FOR( i , 0 , N ){
  //   answer += A[i];
  // }
  // // COUT( answer );
  // // COUT_A( A , N );
  RETURN( answer );

  FINISH_MAIN;
}
0