题解:CF505B Mr. Kitayuta's Colorful Graph
EnjoySilence · · 题解
\textbf{\textit{Problem}}
给定
注意到
现在问题在于:如何计算答案?我们可以在 DFS 的过程中对每个节点存储一个
如果直接对每条端点相同但颜色不同的边做上面的转移,我们会发现节点的访问标记会很混乱(因为存在一个节点被多次更新的情况),于是我们考虑将所有端点相同但颜色不同的边并在一起,将每条边的颜色
最后答案显然就是
让我们分析一下时间复杂度:对于
\textbf{\textit{Code}}
Submission
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
const int N = 105, M = 205;
int n, m, q, u, v;
bool book[N][M], col[N][N][M];
vector<int> g[N];
void dfs(int x) {
for(int y : g[x]) {
bool flag = false;
for(int i = 1; i <= m; i++) {
if((book[x][i] && col[x][y][i]) && !book[y][i]) flag = true;
book[y][i] |= (book[x][i] && col[x][y][i]);
}
if(!flag) continue;
dfs(y);
}
}
void solve() {
cin >> n >> m;
for(int i = 1; i <= m; i++) {
int u, v, w; cin >> u >> v >> w;
g[u].push_back(v), g[v].push_back(u);
col[u][v][w] = col[v][u][w] = true;
}
cin >> q;
while(q--) {
cin >> u >> v;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
book[i][j] = (i == u ? true : false);
dfs(u);
int ans = 0;
for(int i = 1; i <= m; i++) ans += book[v][i];
cout << ans << endl;
}
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int T = 1;
// cin >> T;
while(T--) solve();
return 0;
}