H - Mr. Kitayuta’s Colorful Graph
Time Limit:1000MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u
Submit
Status
Practice
CodeForces 505B
Description
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.
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.
Sample Input
Input
4 5
1 2 1
1 2 2
2 3 1
2 3 3
2 4 3
3
1 2
3 4
1 4
Output
2
1
0
Input
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
Output
1
1
1
1
2
Hint
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.
题意:首行给出N和M,代表有N个点。接下来有M行,每行三个数字A,B,C,代表A到B有颜色为C的绳(也可以是线,随便是什么吧)。接着给出Q,代表Q次询问。接下来Q行,每行给出A和B,只有相同颜色的绳才可以把AB联通,问联通AB的绳子一共有多少种。
思路:map[p][i][j]=1代表i到j被颜色p联通
代码(可以优化的地方很多,不过后台水,就这么过去了)
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;
const int maxn=101;
int map[maxn][maxn][maxn];//初始化为0
int num[maxn];//辅助记录i是否出现过
int N;//N个点
int M;//M条边
int Q;//Q次询问
int main()
{
memset(map,0,sizeof(map));
memset(num,0,sizeof(num));
scanf("%d%d",&N,&M);
int a,b,c;
while(M--)//建图
{
scanf("%d%d%d",&a,&b,&c);
map[c][a][b]=1;//a到b以颜色c联通
map[c][b][a]=1;
//是否记录颜色最值,视情况优化
num[c]=1;//标记此颜色出现过
}
for(int p=1; p<=maxn; p++)//弗洛伊德更新连通性
{
if(num[p])//颜色p出现过
{
for(int k=1; k<=N; k++)
{
for(int i=1; i<=N; i++)
{
for(int j=1; j<=N; j++)
{
if(!map[p][i][j]&&map[p][i][k]&&map[p][k][j])
{
map[p][i][j]=1;
}
}
}
}
}
}
scanf("%d",&Q);
// //打印1到4
// for(int p=1;p<=3;p++)
// {
// for(int i=1;i<=4;i++)
// {
// for(int j=1;j<=4;j++)
// {
// printf("%d ",map[p][i][j]);
// }
// printf("\n");
// }
// printf("\n\n");
// }
while(Q--)
{
int count=0;
scanf("%d%d",&a,&b);
for(int p=1; p<=maxn; p++)
{
if(num[p]==1&&map[p][a][b]==1)
{
count++;
}
}
printf("%d\n",count);
}
return 0;
}