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.
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.
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.
- 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.
题意:
下面有q个询问.
每条询问有两个整数 — ui 和 vi.
找到满足下面条件的颜色个数: 同一种颜色的路径连接顶点 ui 和 顶点 vi
将不同颜色的同一个点看成不同点,开一个二维并查集,既然f[x]储存的是x的父亲节点,那么我们用f[][],第一维表示颜色,第二维便是节点x,我们就用f[c][x]表示与颜色都为c的x的父亲节点,这样,在输入的时候,直接将颜色相同的两个点用并查集联通起来
代码:
#include<stdio.h>
#include<algorithm>
#define MAX 105
using namespace std;
int n,m;
int pre[MAX][MAX];//pre[c][j]表示与颜色都为c的x的父亲节点
void init(){
int i,j;
for(i=0;i<=m;i++)//最多m种颜色
for(j=0;j<=n;j++)//顶点数
pre[i][j]=j; //颜色是i的j点父亲是j点本身
}
int Find(int c,int x){ //寻找颜色为c 的x的父亲
int r=x;
while(r!=pre[c][r])
r=pre[c][r];
int i=x,j;
while(i!=r){ //路径压缩
j=pre[c][i];
pre[c][i]=r;
i=j;
}
return r;
}
void mix(int a,int b,int c){ //将颜色为c的a,b两点连起来
int fa=Find(c,a),fb=Find(c,b);
if(fa!=fb){
pre[c][fb]=fa;
}
}
int sea(int x,int y,int col){ //查看是否颜色为col 的x,y相连
return Find(col,x)==Find(col,y);
}
int main(){
scanf("%d%d",&n,&m);
init();
int i;
int maxx=-1;
for(i=0;i<m;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
maxx=max(maxx,c); //记录所有颜色的最大值
mix(a,b,c);
}
int k;
scanf("%d",&k);
int j;
for(i=0;i<k;i++){
int a,b;
scanf("%d%d",&a,&b);
int cnt=0;
for(j=0;j<=maxx;j++) //枚举颜色,判断是否有同一颜色的a,b相连
cnt+=sea(a,b,j);
printf("%d\n",cnt);
}
return 0;
}