思路:二维并查集,每种颜色维护一个并查集,查询时看某一种颜色下两个点是否有共同的father。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 1005
#define MAXN 2005
#define mod 1000000009
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-6
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
typedef long long ll;
using namespace std;
int n,m;
int color[110];
int father[110][110];
void init()
{
for (int i=0;i<=110;i++)
for (int j=0;j<=110;j++)
father[i][j]=j;
}
int find_father(int c,int x) //递归写法
{
if (x!=father[c][x])
father[c][x]=find_father(c,father[c][x]);
return father[c][x];
}
//int find_father(int c,int x) //非递归写法
//{
// int r=x,i,j;
// while(r!=father[c][r])
// r=father[c][r];
// i=x;
// while(i!=r)
// {
// j=father[c][i];
// father[c][i]=r;
// i=j;
// }
// return r;
//}
int main()
{
while (~scanf("%d%d",&n,&m))
{
init();
int a,b,c;
memset(color,0,sizeof(color)); //记录下用了哪些颜色
for (int i=0;i<m;i++)
{
scanf("%d%d%d",&a,&b,&c);
color[c]=1;
// printf("+++\n");
int fa=find_father(c,a);
int fb=find_father(c,b);
if (fa!=fb)
father[c][fa]=fb;
}
int q,x,y;
scanf("%d",&q);
while (q--)
{
scanf("%d%d",&x,&y);
int ans=0;
for (int i=1;i<=m;i++)
{
if (color[i])
{
if (find_father(i,x)==find_father(i,y))
ans++;
}
}
printf("%d\n",ans);
}
}
return 0;
}