結果

問題 No.650 行列木クエリ
ユーザー ningenMeningenMe
提出日時 2021-04-23 04:19:06
言語 C++17
(gcc 12.3.0 + boost 1.83.0)
結果
AC  
実行時間 153 ms / 2,000 ms
コード長 23,514 bytes
コンパイル時間 3,236 ms
コンパイル使用メモリ 242,128 KB
実行使用メモリ 41,264 KB
最終ジャッジ日時 2023-09-17 10:46:04
合計ジャッジ時間 5,163 ms
ジャッジサーバーID
(参考情報)
judge14 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,376 KB
testcase_01 AC 56 ms
10,380 KB
testcase_02 AC 153 ms
35,908 KB
testcase_03 AC 1 ms
4,380 KB
testcase_04 AC 56 ms
10,420 KB
testcase_05 AC 153 ms
36,008 KB
testcase_06 AC 2 ms
4,376 KB
testcase_07 AC 2 ms
4,380 KB
testcase_08 AC 53 ms
11,304 KB
testcase_09 AC 111 ms
41,264 KB
testcase_10 AC 1 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

#define ALL(obj) (obj).begin(),(obj).end()
#define SPEED cin.tie(0);ios::sync_with_stdio(false);

template <class T, class U>ostream &operator<<(ostream &o, const map<T, U>&obj) {o << "{"; for (auto &x : obj) o << " {" << x.first << " : " << x.second << "}" << ","; o << " }"; return o;}
template <class T>ostream &operator<<(ostream &o, const set<T>&obj) {o << "{"; for (auto itr = obj.begin(); itr != obj.end(); ++itr) o << (itr != obj.begin() ? ", " : "") << *itr; o << "}"; return o;}
template <class T>ostream &operator<<(ostream &o, const multiset<T>&obj) {o << "{"; for (auto itr = obj.begin(); itr != obj.end(); ++itr) o << (itr != obj.begin() ? ", " : "") << *itr; o << "}"; return o;}
template <class T>ostream &operator<<(ostream &o, const vector<T>&obj) {o << "{"; for (int i = 0; i < (int)obj.size(); ++i)o << (i > 0 ? ", " : "") << obj[i]; o << "}"; return o;}
template <class T>ostream &operator<<(ostream &o, const array<T,4>&obj) {o << "{"; for (int i = 0; i < (int)obj.size(); ++i)o << (i > 0 ? ", " : "") << obj[i]; o << "}"; return o;}
template <class T, class U>ostream &operator<<(ostream &o, const pair<T, U>&obj) {o << "{" << obj.first << ", " << obj.second << "}"; return o;}
template <template <class tmp>  class T, class U> ostream &operator<<(ostream &o, const T<U> &obj) {o << "{"; for (auto itr = obj.begin(); itr != obj.end(); ++itr)o << (itr != obj.begin() ? ", " : "") << *itr; o << "}"; return o;}
void print(void) {cout << endl;}
template <class Head> void print(Head&& head) {cout << head;print();}
template <class Head, class... Tail> void print(Head&& head, Tail&&... tail) {cout << head << " ";print(forward<Tail>(tail)...);}
constexpr long long MOD = 1000000007;

/*
 * @title Graph
 * @docs md/graph/Graph.md
 */
template<class T> class Graph{
private:
    const size_t N,H,W;
public:
    vector<vector<pair<size_t,T>>> edges;
    Graph(const size_t N):H(-1),W(-1),N(N), edges(N) {}
    Graph(const size_t H, const size_t W):H(H),W(W),N(H*W), edges(H*W) {}
    inline void make_edge(size_t from, size_t to, T w) {
        edges[from].emplace_back(to,w);
    }
    //{from_y,from_x} -> {to_y,to_x} 
    inline void make_edge(pair<size_t,size_t> from, pair<size_t,size_t> to, T w) {
        make_edge(from.first*W+from.second,to.first*W+to.second,w);
    }
    inline void make_bidirectional_edge(size_t from, size_t to, T w) {
        make_edge(from,to,w);
        make_edge(to,from,w);
    }
    inline void make_bidirectional_edge(pair<size_t,size_t> from, pair<size_t,size_t> to, T w) {
        make_edge(from.first*W+from.second,to.first*W+to.second,w);
        make_edge(to.first*W+to.second,from.first*W+from.second,w);
    }
    inline size_t size(){return N;}
    inline size_t idx(pair<size_t,size_t> yx){return yx.first*W+yx.second;}
};

/*
 * @title ModInt
 * @docs md/util/ModInt.md
 */
template<long long mod> class ModInt {
public:
    long long x;
    constexpr ModInt():x(0) {}
    constexpr ModInt(long long y) : x(y>=0?(y%mod): (mod - (-y)%mod)%mod) {}
    ModInt &operator+=(const ModInt &p) {if((x += p.x) >= mod) x -= mod;return *this;}
    ModInt &operator+=(const long long y) {ModInt p(y);if((x += p.x) >= mod) x -= mod;return *this;}
    ModInt &operator+=(const int y) {ModInt p(y);if((x += p.x) >= mod) x -= mod;return *this;}
    ModInt &operator-=(const ModInt &p) {if((x += mod - p.x) >= mod) x -= mod;return *this;}
    ModInt &operator-=(const long long y) {ModInt p(y);if((x += mod - p.x) >= mod) x -= mod;return *this;}
    ModInt &operator-=(const int y) {ModInt p(y);if((x += mod - p.x) >= mod) x -= mod;return *this;}
    ModInt &operator*=(const ModInt &p) {x = (x * p.x % mod);return *this;}
    ModInt &operator*=(const long long y) {ModInt p(y);x = (x * p.x % mod);return *this;}
    ModInt &operator*=(const int y) {ModInt p(y);x = (x * p.x % mod);return *this;}
    ModInt &operator^=(const ModInt &p) {x = (x ^ p.x) % mod;return *this;}
    ModInt &operator^=(const long long y) {ModInt p(y);x = (x ^ p.x) % mod;return *this;}
    ModInt &operator^=(const int y) {ModInt p(y);x = (x ^ p.x) % mod;return *this;}
    ModInt &operator/=(const ModInt &p) {*this *= p.inv();return *this;}
    ModInt &operator/=(const long long y) {ModInt p(y);*this *= p.inv();return *this;}
    ModInt &operator/=(const int y) {ModInt p(y);*this *= p.inv();return *this;}
    ModInt operator=(const int y) {ModInt p(y);*this = p;return *this;}
    ModInt operator=(const long long y) {ModInt p(y);*this = p;return *this;}
    ModInt operator-() const {return ModInt(-x); }
    ModInt operator++() {x++;if(x>=mod) x-=mod;return *this;}
    ModInt operator--() {x--;if(x<0) x+=mod;return *this;}
    ModInt operator+(const ModInt &p) const { return ModInt(*this) += p; }
    ModInt operator-(const ModInt &p) const { return ModInt(*this) -= p; }
    ModInt operator*(const ModInt &p) const { return ModInt(*this) *= p; }
    ModInt operator/(const ModInt &p) const { return ModInt(*this) /= p; }
    ModInt operator^(const ModInt &p) const { return ModInt(*this) ^= p; }
    bool operator==(const ModInt &p) const { return x == p.x; }
    bool operator!=(const ModInt &p) const { return x != p.x; }
    ModInt inv() const {int a=x,b=mod,u=1,v=0,t;while(b > 0) {t = a / b;swap(a -= t * b, b);swap(u -= t * v, v);} return ModInt(u);}
    ModInt pow(long long n) const {ModInt ret(1), mul(x);for(;n > 0;mul *= mul,n >>= 1) if(n & 1) ret *= mul;return ret;}
    friend ostream &operator<<(ostream &os, const ModInt &p) {return os << p.x;}
    friend istream &operator>>(istream &is, ModInt &a) {long long t;is >> t;a = ModInt<mod>(t);return (is);}
};
using modint = ModInt<MOD>;

/*
 * @title Matrix - 行列演算
 * @docs md/math/Matrix.md
 */
template <class T, int H, int W = H> class Matrix {
public:
	int h,w;
	array<array<T,W>,H> a;
	Matrix():h(H),w(W){
		// do nothing
	}
	Matrix(const vector<vector<T>>& vec):h(H),w(W) {
		assert(vec.size()==H && vec.front().size()==W);
		for(int i = 0; i < H; ++i) for(int j = 0; j < W; ++j) a[i][j]=vec[i][j];
	}
	static Matrix E() {
		assert(H==W);
		Matrix res = Matrix();
		for(int i = 0; i < H; ++i) res[i][i]=1;
		return res;
	}
	Matrix &operator+=(const Matrix &r) {
		assert(H==r.h&&W==r.w);
		for(int i = 0; i < H; ++i) for(int j = 0; j < W; ++j) a[i][j]+=r[i][j];
		return *this;
	}
	Matrix &operator-=(const Matrix &r) {
		assert(H==r.h&&W==r.w);
		for(int i = 0; i < H; ++i) for(int j = 0; j < W; ++j) a[i][j]-=r[i][j];
		return *this;
	}
	Matrix &operator*=(const Matrix &r) {
		assert(W==r.h);
		Matrix res = Matrix();
		for(int i = 0; i < H; ++i) for(int j = 0; j < r.w; ++j) for(int k = 0; k < W; ++k) res[i][j]+=(a[i][k])*(r[k][j]);
		a.swap(res.a);
		return *this;
	}
	Matrix operator+(const Matrix& r) const {
		return Matrix(*this) += r;
	}
	Matrix operator-(const Matrix& r) const {
		return Matrix(*this) -= r;
	}
	Matrix operator*(const Matrix& r) const {
		return Matrix(*this) *= r;
	}
	inline array<T,W> &operator[](int i) { 
		return a[i];
	}
	inline const array<T,W> &operator[](int i) const { 
		return a[i];
	}
	Matrix pow(long long K) const {
		assert(H == W);
		Matrix x(*this);
		Matrix res = this->E();
		for (; K > 0; K /= 2) {
			if (K & 1) res *= x;
			x *= x;
		}
		return res;
	}
	T determinant(void) const {
		assert(H==W);
		Matrix x(*this);
		T res = 1;
		for(int i = 0; i < H; i++) {
			int idx = -1;
			for(int j = i; j < W; j++) if(x[j][i] != 0) idx = j;
			if(idx == -1) return 0;
			if(i != idx) {
				res *= -1;
				swap(x[i], x[idx]);
			}
			res *= x[i][i];
			T tmp = x[i][i];
			for(int j = 0; j < W; ++j) x[i][j] /= tmp;
			for(int j = i + 1; j < H; j++) {
				tmp = x[j][i];
				for(int k = 0; k < W; k++) x[j][k] -= x[i][k]*tmp;
			}
		}
		return res;
	}
};


/*
 * @title Tree - 木
 * @docs md/graph/Tree.md
 */
template<class Operator> class TreeBuilder;
template<class Operator> class Tree {
	using TypeEdge = typename Operator::TypeEdge;
	size_t num;
	size_t ord;
	Graph<TypeEdge>& g;
	friend TreeBuilder<Operator>;
	Tree(Graph<TypeEdge>& graph):
		g(graph),
		num(graph.size()),
		depth(graph.size(),-1),
		order(graph.size()),
		edge_dist(graph.size()){
	}
	//for make_depth
	void dfs(int curr, int prev){
		for(const auto& e:g.edges[curr]){
			const int& next = e.first;
			if(next==prev) continue;
			depth[next] = depth[curr] + 1;
			edge_dist[next]  = Operator::func_edge_merge(edge_dist[curr],e.second);
			dfs(next,curr);
			order[ord++] = next;
		}
	}
	//for make_eulertour
	void dfs(int from){
		eulertour.push_back(from);
		for(auto& e:child[from]){
			int to = e.first;            
			dfs(to);        
			eulertour.push_back(from);
		}
	}
	void make_root(const int root) {
		depth[root] = 0;
		edge_dist[root] = Operator::unit_edge;
		ord = 0;
		dfs(root,-1);
		order[ord++] = root;
		reverse_copy(order.begin(),order.end(),back_inserter(reorder));
	}
	void make_root() {
        ord = 0;
        for(int i=0;i<num;++i) {
            if(depth[i]!=-1) continue;
            depth[i] = 0;
            edge_dist[i] = Operator::unit_edge;
            dfs(i,-1);
            order[ord++] = i;
        }
		reverse_copy(order.begin(),order.end(),back_inserter(reorder));
	}
	void make_child(const int root = 0) {
		child.resize(num);
		for (size_t i = 0; i < num; ++i) for (auto& e : g.edges[i]) if (depth[i] < depth[e.first]) child[i].push_back(e);
	}
	void make_subtree_size() {
		subtree_size.resize(num,1);
		for (size_t i:order) for (auto e : child[i]) subtree_size[i] += subtree_size[e.first];
	}
	void make_parent() {
		parent.resize(num,make_pair(num,Operator::unit_edge));
		for (size_t i = 0; i < num; ++i) for (auto& e : g.edges[i]) if (depth[i] > depth[e.first]) parent[i] = e;
	}
	void make_ancestor() {
		ancestor.resize(num);
		for (size_t i = 0; i < num; ++i) ancestor[i][0] = (parent[i].first!=num?parent[i]:make_pair(i,Operator::unit_lca_edge));
		for (size_t j = 1; j < Operator::bit; ++j) {
			for (size_t i = 0; i < num; ++i) {
				size_t k = ancestor[i][j - 1].first;
				ancestor[i][j] = Operator::func_lca_edge_merge(ancestor[k][j - 1],ancestor[i][j - 1]);
			}
		}
	}
	pair<size_t,TypeEdge> lca_impl(size_t l, size_t r) {
		if (depth[l] < depth[r]) swap(l, r);
		int diff = depth[l] - depth[r];
		auto ancl = make_pair(l,Operator::unit_lca_edge);
		auto ancr = make_pair(r,Operator::unit_lca_edge);
		for (int j = 0; j < Operator::bit; ++j) {
			if (diff & (1 << j)) ancl = Operator::func_lca_edge_merge(ancestor[ancl.first][j],ancl);
		}
		if(ancl.first==ancr.first) return ancl;
		for (int j = Operator::bit - 1; 0 <= j; --j) {
			if(ancestor[ancl.first][j].first!=ancestor[ancr.first][j].first) {
				ancl = Operator::func_lca_edge_merge(ancestor[ancl.first][j],ancl);
				ancr = Operator::func_lca_edge_merge(ancestor[ancr.first][j],ancr);
			}
		}
		ancl = Operator::func_lca_edge_merge(ancestor[ancl.first][0],ancl);
		ancr = Operator::func_lca_edge_merge(ancestor[ancr.first][0],ancr);
		return Operator::func_lca_edge_merge(ancl,ancr);
	}
	pair<TypeEdge,vector<size_t>> diameter_impl() {
		Tree tree = Tree::builder(g).build();
		size_t root = 0;
		{
			tree.make_root(0);
		}
		root = max_element(tree.edge_dist.begin(),tree.edge_dist.end()) - tree.edge_dist.begin();
		{
			tree.make_root(root);
		}
		size_t leaf = max_element(tree.edge_dist.begin(),tree.edge_dist.end()) - tree.edge_dist.begin();
		TypeEdge sz = tree.edge_dist[leaf];
		vector<size_t> st;
		{
			tree.make_parent();
			while(leaf != root) {
				st.push_back(leaf);
				leaf = tree.parent[leaf].first;
			}
			st.push_back(root);
		}
		return make_pair(sz,st);
	}
	template<class TypeReroot> vector<TypeReroot> rerooting_impl(vector<TypeReroot> rerootdp,vector<TypeReroot> rerootparent) {
		for(size_t pa:order) for(auto& e:child[pa]) rerootdp[pa] = Operator::func_reroot_dp(rerootdp[pa],rerootdp[e.first]);
		for(size_t pa:reorder) {
			if(depth[pa]) rerootdp[pa] = Operator::func_reroot_dp(rerootdp[pa],rerootparent[pa]);
			size_t m = child[pa].size();
			for(int j = 0; j < m && depth[pa]; ++j){
				size_t ch = child[pa][j].first;
				rerootparent[ch] = Operator::func_reroot_dp(rerootparent[ch],rerootparent[pa]);
			}
			if(m <= 1) continue;
			vector<TypeReroot> l(m),r(m);
			for(int j = 0; j < m; ++j) {
				size_t ch = child[pa][j].first;
				l[j] = rerootdp[ch];
				r[j] = rerootdp[ch];
			}
			for(int j = 1; j+1 < m; ++j) l[j] = Operator::func_reroot_merge(l[j],l[j-1]);
			for(int j = m-2; 0 <=j; --j) r[j] = Operator::func_reroot_merge(r[j],r[j+1]);
			size_t chl = child[pa].front().first;
			size_t chr = child[pa].back().first;
			rerootparent[chl] = Operator::func_reroot_dp(rerootparent[chl],r[1]);
			rerootparent[chr] = Operator::func_reroot_dp(rerootparent[chr],l[m-2]);
			for(int j = 1; j+1 < m; ++j) {
				size_t ch = child[pa][j].first;
				rerootparent[ch] = Operator::func_reroot_dp(rerootparent[ch],l[j-1]);
				rerootparent[ch] = Operator::func_reroot_dp(rerootparent[ch],r[j+1]);
			}
		}
		return rerootdp;
	}
	void make_eulertour() {
		dfs(reorder.front());
		eulertour_range.resize(num);
		for(int i = 0; i < eulertour.size(); ++i) eulertour_range[eulertour[i]].second = i+1;
		for(int i = eulertour.size()-1; 0 <= i; --i) eulertour_range[eulertour[i]].first = i;
	}
	void make_heavy_light_decomposition(){
		head.resize(num);
		hld.resize(num);
		iota(head.begin(),head.end(),0);
		for(size_t& pa:reorder) {
			pair<size_t,size_t> maxi = {0,num};
			for(auto& p:child[pa]) maxi = max(maxi,{subtree_size[p.first],p.first});
			if(maxi.first) head[maxi.second] = head[pa];
		}
		stack<size_t> st_head,st_sub;
		size_t cnt = 0;
		//根に近い方から探索
		for(size_t& root:reorder){
			if(depth[root]) continue;
			//根をpush
			st_head.push(root);
			while(st_head.size()){
				size_t h = st_head.top();
				st_head.pop();
				//部分木の根をpush
				st_sub.push(h);
				while (st_sub.size()){
					size_t pa = st_sub.top();
					st_sub.pop();
					//部分木をカウントしていく
					hld[pa] = cnt++;
					//子を探索
					for(auto& p:child[pa]) {
						//子のheadが親と同じなら、そのまま進む
						if(head[p.first]==head[pa]) st_sub.push(p.first);
						//そうじゃない場合は、そこから新しく部分木としてみなす
						else st_head.push(p.first);
					}
				}				
			}
		}
	}
	//type 0: vertex, 1: edge
	vector<pair<size_t,size_t>> path(size_t u,size_t v,int type = 0) {
		vector<pair<size_t,size_t>> path;
		while(1){
			if(hld[u]>hld[v]) swap(u,v);
			if(head[u]!=head[v]) {
				path.push_back({hld[head[v]],hld[v]});
				v=parent[head[v]].first;
			}
			else {
				path.push_back({hld[u],hld[v]});
				break;
			}
		}
		reverse(path.begin(),path.end());
		if(type) path.front().first++;
		return path;
	}
	vector<size_t> head;
public:
	vector<size_t> depth;
	vector<size_t> order;
	vector<size_t> reorder;
	vector<size_t> subtree_size;
	vector<pair<size_t,TypeEdge>> parent;
	vector<vector<pair<size_t,TypeEdge>>> child;
	vector<TypeEdge> edge_dist;
	vector<array<pair<size_t,TypeEdge>,Operator::bit>> ancestor;
	vector<size_t> eulertour;
	vector<pair<size_t,size_t>> eulertour_range;
	vector<size_t> hld;

	/**
	 * O(N) builder
	 */
	static TreeBuilder<Operator> builder(Graph<TypeEdge>& graph) { return TreeBuilder<Operator>(graph);}
	/**
	 * O(logN) after make_ancestor
	 * return {lca,lca_dist} l and r must be connected 
	 */
	pair<size_t,TypeEdge> lca(size_t l, size_t r) {return lca_impl(l,r);}
	/**
	 * O(N) anytime
	 * return {diameter size,diameter set} 
	 */
	pair<TypeEdge,vector<size_t>> diameter(void){return diameter_impl();}
	/**
	 * O(N) after make_child
	 */
	template<class TypeReroot> vector<TypeReroot> rerooting(const vector<TypeReroot>& rerootdp,const vector<TypeReroot>& rerootparent) {return rerooting_impl(rerootdp,rerootparent);}
	/**
	 * O(logN) 
	 */
	vector<pair<size_t,size_t>> vertex_set_on_path(size_t u, size_t v) {return path(u,v,0);}
	/**
	 * O(logN) 
	 */
	vector<pair<size_t,size_t>> edge_set_on_path(size_t u, size_t v) {return path(u,v,1);}
};
 
template<class Operator> class TreeBuilder {
	bool is_root_made =false;
	bool is_child_made =false;
	bool is_parent_made=false;
	bool is_subtree_size_made=false;
public:
	using TypeEdge = typename Operator::TypeEdge;
	TreeBuilder(Graph<TypeEdge>& g):tree(g){}
	TreeBuilder& root(const int rt) { is_root_made=true; tree.make_root(rt); return *this;}
	TreeBuilder& root() { is_root_made=true; tree.make_root(); return *this;}
	TreeBuilder& child() { assert(is_root_made); is_child_made=true;  tree.make_child();  return *this;}
	TreeBuilder& parent() { assert(is_root_made); is_parent_made=true; tree.make_parent(); return *this;}
	TreeBuilder& subtree_size() { assert(is_child_made); is_subtree_size_made=true; tree.make_subtree_size(); return *this;}
	TreeBuilder& ancestor() { assert(is_parent_made); tree.make_ancestor(); return *this;}
	TreeBuilder& eulertour() { assert(is_child_made); tree.make_eulertour(); return *this;}
	TreeBuilder& heavy_light_decomposition() { assert(is_subtree_size_made); assert(is_parent_made); tree.make_heavy_light_decomposition(); return *this;}
	Tree<Operator>&& build() {return move(tree);}
private:
	Tree<Operator> tree;
}; 
template<class T> struct TreeOperator{
	using TypeEdge = T;
	inline static constexpr size_t bit = 20;
	inline static constexpr TypeEdge unit_edge = 0;
	inline static constexpr TypeEdge unit_lca_edge = 0;
	inline static constexpr TypeEdge func_edge_merge(const TypeEdge& parent,const TypeEdge& w){return parent+w;}
	inline static constexpr pair<size_t,TypeEdge> func_lca_edge_merge(const pair<size_t,TypeEdge>& l,const pair<size_t,TypeEdge>& r){return make_pair(l.first,l.second+r.second);}
	template<class TypeReroot> inline static constexpr TypeReroot func_reroot_dp(const TypeReroot& l,const TypeReroot& r) {return {l.first+r.first+r.second,l.second+r.second};}
	template<class TypeReroot> inline static constexpr TypeReroot func_reroot_merge(const TypeReroot& l,const TypeReroot& r) {return {l.first+r.first,l.second+r.second};}
};

/*
 * @title SegmentTree - 非再帰抽象化セグメント木
 * @docs md/segment/SegmentTree.md
 */
template<class Operator> class SegmentTree {
    using TypeNode = typename Operator::TypeNode; 
    size_t length;
    size_t num;
    vector<TypeNode> node;
    vector<pair<int,int>> range;
    inline void build() {
        for (int i = length - 1; i >= 0; --i) node[i] = Operator::func_node(node[(i<<1)+0],node[(i<<1)+1]);
        range.resize(2 * length);
        for (int i = 0; i < length; ++i) range[i+length] = make_pair(i,i+1);
        for (int i = length - 1; i >= 0; --i) range[i] = make_pair(range[(i<<1)+0].first,range[(i<<1)+1].second);
    }
public:

    //unitで初期化
    SegmentTree(const size_t num): num(num) {
        for (length = 1; length <= num; length *= 2);
        node.resize(2 * length, Operator::unit_node);
        build();
    }

    //vectorで初期化
    SegmentTree(const vector<TypeNode> & vec) : num(vec.size()) {
        for (length = 1; length <= vec.size(); length *= 2);
        node.resize(2 * length, Operator::unit_node);
        for (int i = 0; i < vec.size(); ++i) node[i + length] = vec[i];
        build();
    }
 
    //同じinitで初期化
    SegmentTree(const size_t num, const TypeNode init) : num(num) {
        for (length = 1; length <= num; length *= 2);
        node.resize(2 * length, Operator::unit_node);
        for (int i = 0; i < length; ++i) node[i+length] = init;
        build();
    }
    
    //[idx,idx+1)
    void update(size_t idx, const TypeNode var) {
        if(idx < 0 || length <= idx) return;
        idx += length;
        node[idx] = Operator::func_merge(node[idx],var);
        while(idx >>= 1) node[idx] = Operator::func_node(node[(idx<<1)+0],node[(idx<<1)+1]);
    }

    //[l,r)
    TypeNode get(int l, int r) {
        if (l < 0 || length <= l || r < 0 || length < r) return Operator::unit_node;
        TypeNode vl = Operator::unit_node, vr = Operator::unit_node;
        for(l += length, r += length; l < r; l >>=1, r >>=1) {
            if(l&1) vl = Operator::func_node(vl,node[l++]);
            if(r&1) vr = Operator::func_node(node[--r],vr);
        }
        return Operator::func_node(vl,vr);
    }

    //range[l,r) return [l,r] search max right
    int prefix_binary_search(int l, int r, TypeNode var) {
        assert(0 <= l && l < length && 0 < r && r <= length);
        TypeNode ret = Operator::unit_node;
        size_t off = l;
        for(size_t idx = l+length; idx < 2*length && off < r; ){
            if(range[idx].second<=r && !Operator::func_check(Operator::func_node(ret,node[idx]),var)) {
                ret = Operator::func_node(ret,node[idx]);
                off = range[idx++].second;
                if(!(idx&1)) idx >>= 1;			
            }
            else{
                idx <<=1;
            }
        }
        return off;
    }

    //range(l,r] return [l,r] search max left
    int suffix_binary_search(const int l, const int r, const TypeNode var) {
        assert(-1 <= l && l < (int)length-1 && 0 <= r && r < length);
        TypeNode ret = Operator::unit_node;
        int off = r;
        for(size_t idx = r+length; idx < 2*length && l < off; ){
            if(l < range[idx].first && !Operator::func_check(Operator::func_node(node[idx],ret),var)) {
                ret = Operator::func_node(node[idx],ret);
                off = range[idx--].first-1;
                if(idx&1) idx >>= 1;
            }
            else{
                idx = (idx<<1)+1;
            }
        }
        return off;
    }

    void print(){
        // cout << "node" << endl;
        // for(int i = 1,j = 1; i < 2*length; ++i) {
        // 	cout << node[i] << " ";
        // 	if(i==((1<<j)-1) && ++j) cout << endl;
        // }
        cout << "vector" << endl;
        cout << "{ " << get(0,1);
        for(int i = 1; i < length; ++i) cout << ", " << get(i,i+1);
        cout << " }" << endl;
    }
};

//一点更新 区間最小
template<class T> struct NodeMulPointUpdate {
    using TypeNode = T;
    inline static TypeNode unit_node = Matrix<modint,2,2>::E();
    inline static constexpr TypeNode func_node(TypeNode l,TypeNode r){return l*r;}
    inline static constexpr TypeNode func_merge(TypeNode l,TypeNode r){return r;}
    inline static constexpr bool func_check(TypeNode nodeVal,TypeNode var){return var > nodeVal;}
};

using matrix = Matrix<modint,2,2>;
int main() {
	SPEED
	int N; cin >> N;
	Graph<int> g(N);
	vector<pair<size_t,size_t>> vp(N-1);
	for(int i = 0; i < N-1; ++i) {
		int u,v; cin >> u >> v;
		g.make_bidirectional_edge(u,v,1);
		vp[i]={u,v};
	}
	auto tree = Tree<TreeOperator<int>>::builder(g).root(0).child().subtree_size().parent().heavy_light_decomposition().build();
    SegmentTree<NodeMulPointUpdate<matrix>> seg(N);
    int Q; cin >> Q;
    while(Q--) {
        char c; cin >> c;
        if(c == 'x'){
            int i; cin >> i;
            modint a,b,c,d; cin >> a >> b >> c >> d;
            matrix x;
			x[0]={a,b};
			x[1]={c,d};
			int l = vp[i].first, r = vp[i].second;
            l = tree.hld[l],r = tree.hld[r];
            seg.update(max(l,r),x);
        }
        else{
            int l,r; cin >> l >> r;
            auto vp = tree.edge_set_on_path(l,r);
            matrix ans = matrix::E();
            for(auto p:vp){
                ans *= seg.get(p.first,p.second+1);
            }
            cout << ans[0][0] << " " << ans[0][1] << " " << ans[1][0] << " " << ans[1][1] << endl;
        }
    }
	return 0;
}
0