codeforces 505B——DFS——Mr. Kitayuta's Colorful Graph
3484 단어 codeforces
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.
/*
: i j ( )
,
i,j dfs
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
int map[110][110];
int vis[110];
int vis1[110][110];
int color[110][110][110];
vector<int> G[110];
int sum;
bool dfs(int u,int vv,int color1)
{
if(!vis[u]){
vis[u] = 1;
if(u == vv) return true;
for(int i = 0 ; i < G[u].size(); i++){
int v = G[u][i];
for(int j = 1 ; j <= vis1[u][v]; j++){
if(color[u][v][j] == color1){
if( dfs(v, vv, color1)) return true;
}
}
}
}
return false ;
}
int main()
{
int n, m, k;
int a, b, c;
while(~scanf("%d %d", &n, &m)){
memset(vis, 0, sizeof(vis1));
for(int i= 1; i <= m; i++){
scanf("%d%d%d", &a, &b, &c);
G[a].push_back(b);
G[b].push_back(a);
vis1[a][b]++;
vis1[b][a]++;
color[a][b][vis1[a][b]] = c;
color[b][a][vis1[b][a]] = c;
}
scanf("%d", &k);
int v1, v2;
while(k--){
sum = 0;
scanf("%d%d", &v1, &v2);
for(int i = 1; i <= m; i++){
memset(vis, 0, sizeof(vis));
if(dfs(v1, v2, i)){
sum++;
}
}
printf("%d
", sum);
}
}
return 0;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Codeforces Round #715 Div. 2C The Sports Festival: 구간 DP전형구간 DP의 초전형. 이하, 0-indexed. 입력을 정렬하여 어디서나 시작하고 최적으로 좌우로 계속 유지하면 좋다는 것을 알 수 있습니다. {2000})$의 주문이 된다. 우선, 입력을 소트하여 n개의 요소를 $...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.