Mr. Kitayuta has just bought an undirected graph with n vertices and m edges. The vertices of the graph are numbered from 1 to n. Each edge, namely edge i, has a color ci, connecting vertex ai and bi.
Mr. Kitayuta wants you to process the following q queries.
In the i-th query, he gives you two integers - ui and vi.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex ui and vertex vi directly or indirectly.
The first line of the input contains space-separated two integers - n and m(2 ≤ n ≤ 105, 1 ≤ m ≤ 105), denoting the number of the vertices and the number of the edges, respectively.
The next m lines contain space-separated three integers - ai, bi(1 ≤ ai < bi ≤ n) and ci(1 ≤ ci ≤ m). Note that there can be multiple edges between two vertices. However, there are no multiple edges of the same color between two vertices, that is, ifi ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer- q(1 ≤ q ≤ 105), denoting the number of the queries.
Then follows q lines, containing space-separated two integers - ui and vi(1 ≤ ui, vi ≤ n). It is guaranteed that ui ≠ vi.
For each query, print the answer in a separate line.
4 5 1 2 1 1 2 2 2 3 1 2 3 3 2 4 3 3 1 2 3 4 1 4
2 1 0
5 7 1 5 1 2 5 1 3 5 1 4 5 1 1 2 2 2 3 2 3 4 2 5 1 5 5 1 2 5 1 5 1 4
1 1 1 1 2
Let's consider the first sample.
题意是给出了通过不同颜色的边连接的一些点,有Q个查询,查询两个点可以用多少种不同颜色的边连接起来。
如果是一个颜色的边,然后Q个询问,询问两个点是否被连接,可以离线并查集搞。现在是m个颜色的边,那就一个一个颜色并查集搞。
但是,这里还是有问题,就是如何输出结果,这里也学习到了新姿势。就是如果这个颜色的点很多的话,那就遍历Q个查询,记录结果。如果这个颜色的点很少的话,那就O(n^2)记录这些颜色的点。
代码:
#pragma warning(disable:4996)
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include