#include using namespace std; class UnionFind{ private: vector par,siz; public: UnionFind(int N){ par.resize(N,-1); siz.resize(N,1); } int root(int x){ //連結成分の代表頂点を返す. if(par.at(x) == -1) return x; else return par.at(x) = root(par.at(x)); } bool unite(int u, int v){ //u,vを連結する 連結してた->false,した->trueを返す. u = root(u),v = root(v); if(u == v) return false; if(siz.at(u) < siz.at(v)) swap(u,v); //Union by size. par.at(v) = u; siz.at(u) += siz.at(v); return true; } bool issame(int u, int v){ //同じ連結成分ならtrue. if(root(u) == root(v)) return true; else return false; } int size(int pos){return siz.at(root(pos));} //posの連結成分の大きさを返す. }; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); int N,M; cin >> N >> M; vector> edge(M); for(auto &[a,b,c] : edge) cin >> b >> c >> a,b--,c--; sort(edge.begin(),edge.end()); int Q; cin >> Q; vector answer(Q); vector> Query(Q); for(int i=0; i> p >> t,t--; Query.at(i) = {p,t,i}; } sort(Query.begin(),Query.end()); int epos = 0; UnionFind Z(N); for(auto [p,t,qpos] : Query){ while(epos < M){ auto [a,u,v] = edge.at(epos); if(a <= p) Z.unite(u,v),epos++; else break; } answer.at(qpos) = Z.size(t); } for(auto a : answer) cout << a << "\n"; }