Mr. Kitayuta's Colorful Graph
Mr. Kitayuta has just bought an undirected graph consisting of n vertices and medges. 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.
Example
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
Note
Let's consider 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.
题意:有多条不同颜色的路径,求给定两点间相同颜色的路径条数。
思路:由于数据范围不大,可以开一个二维数组,使用二维并查集来处理多个相交的连通块。f[i][j],i表示颜色,f[i][j]表示j的祖先。枚举每种color,当两点祖先相同时,即为有这种color路径使他们连通。
#include<stdio.h> int f[105][105]; int find(int c,int x) { return f[c][x]==x?x:f[c][x]=find(c,f[c][x]); } void join(int c,int x,int y) { int fx=find(c,f[c][x]),fy=find(c,f[c][y]); if(fx!=fy) f[c][fy]=fx; } int main() { int n,m,q,a,b,c,type,cc,i,j; scanf("%d%d",&n,&m); type=0; for(i=1;i<=101;i++){ for(j=1;j<=101;j++){ f[i][j]=j; } } for(i=1;i<=m;i++){ scanf("%d%d%d",&a,&b,&c); if(c>type) type=c; join(c,a,b); } scanf("%d",&q); for(i=1;i<=q;i++){ scanf("%d%d",&a,&b); cc=0; for(j=1;j<=type;j++){ if(find(j,f[j][a])==find(j,f[j][b])) cc++; } printf("%d ",cc); } return 0; }