CodeForces - 505B Mr. Kitayuta's Colorful Graph 二维并查集

it2026-08-17  7

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 — aibi (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

Input 4 51 2 11 2 22 3 12 3 32 4 331 23 41 4 Output 210 Input 5 71 5 12 5 13 5 14 5 11 2 22 3 23 4 251 55 12 51 51 4 Output 11112

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.

 

题意:有多条不同颜色的路径,求给定两点间相同颜色的路径条数。

思路:由于数据范围不大,可以开一个二维数组,使用二维并查集来处理多个相交的连通块。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\n",cc); } return 0; }

 

转载于:https://www.cnblogs.com/yzm10/p/7346194.html

最新回复(0)