Mr. Kitayuta has just bought an undirected graph consisting of 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.
Input
The first line of the input contains space-separated two integers — n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100), 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, if i ≠ j, (ai, bi, ci) ≠ (aj, bj, cj).
The next line contains a integer — q (1 ≤ q ≤ 100), 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.
Output
For each query, print the answer in a separate line.
Examples
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
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
Output
1
1
1
1
2
Note
Let's consider the first sample.
The figure above shows the first sample.
- Vertex 1 and vertex 2 are connected by color 1 and 2.
- Vertex 3 and vertex 4 are connected by color 3.
- Vertex 1 and vertex 4 are not connected by any single color.
题意:有n个点和m条线,a点和b点之间用c颜色的线相连,在给定的数据连完后,进行q次查询,问从x到y点之间有多少种连线方式。
思路:这个题很像以前的并查集,不过多了一些条件限制,因此我们就要将并查集升级一下了。平常并查集f[i]只是代表这个点的祖宗。由于多了颜色的限制,我们就要把一维变成二维,第二维是颜色(f[i][j] 第i个节点,第j种颜色),查询的时候遍历每种颜色即可。
代码如下:
#include<cstdio>
#include<cstring>
int f[110][110];//f[i][j] 第i个节点,第j种颜色
void init() //初始化并查集
{
for(int i=0;i<=100;i++) //点
for(int j=0;j<=100;j++) //颜色
f[i][j]=i;
}
int getf(int u,int v)//u是点,v是颜色
{
if(f[u][v]==u)
return u;
return f[u][v]=getf(f[u][v],v);
}
void merge(int x,int y,int z)
{
int t1=getf(x,z);
int t2=getf(y,z);
if(t1!=t2) //根不同
f[t2][z]=t1;
}
int main()
{
int n,m,q;
int x,y,z;
init();
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&x,&y,&z);
merge(x,y,z); //并查集
}
scanf("%d",&q);
for(int i=0;i<q;i++)
{
scanf("%d%d",&x,&y);
int ans=0;
for(int j=1;j<=m;j++)//遍历每一种颜色
{
int t1=getf(x,j);
int t2=getf(y,j);
if(t1==t2) //在一个集合
ans++;
}
printf("%d\n",ans);
}
}