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.
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.
思路:之前学过并查集,一维的并查集的在这里不适用(考试时,我都没想到用并查集啊)。没想到是个二维的。一看过程,发现还挺简单,代码很简单,思路很清晰(但考试时就是没想到)。
#include <stdio.h>
#include <string.h>
int a[110][110];
int n,m;
int find(int x,int k)
{
if(a[x][k]==x)
return x;
return a[x][k]=find(a[x][k],k);
}
int merge(int x,int y,int z)
{
int tx=find(x,z);
int ty=find(y,z);
if(tx!=ty)
a[tx][z]=ty;
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
int x,y,z;
for(int i=1; i<=100; i++)
for(int j=1; j<=100; j++)
a[i][j]=i;
for(int i=1; i<=m; i++)
{
scanf("%d %d %d",&x,&y,&z);
merge(x,y,z);
}
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&x,&y);
int sum=0;
for(int i=1; i<=m; i++)
if(find(x,i)==find(y,i))
sum++;
printf("%d\n",sum);
}
}
return 0;
}
考试的时候我用的floyd算法,结果做错了,现在想想,发现自己理解有错误,开三维数组,加一个四层for循环这些都没错,错在我的floyd算法错误和累加数值上,因为开的是三维的,不需要累加(因为数组较全,包含所有情况)还有写算法的时候应该注意一下不要写错。
#include <stdio.h>
#include <string.h>
int map[110][110][110];
int n,m;
int main()
{
while(~scanf("%d %d",&n,&m))
{
int x,y,z;
memset(map,0,sizeof(map));
for(int i=0; i<m; i++)
{
scanf("%d %d %d",&x,&y,&z);
map[x][y][z]=1;
map[y][x][z]=1;
}
for(int s=1; s<=m; s++)
{
for(int k=1; k<=n; k++)
{
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
if(map[i][k][s]==1&&map[k][j][s]==1)
{
map[i][j][s]=1;
map[j][i][s]=1;
}
}
}
}
}
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&x,&y);
int sum=0;
for(int i=1; i<=m; i++)
if(map[x][y][i]==1)
sum++;
printf("%d\n",sum);
}
}
return 0;
}