题意:一个森林,询问两个节点距离,若无法到达,输出Not connected。
思路:还是求LCA的思想,只需再对每个询问的两个节点判断是否在一棵树内即可。
有一个问题是这道题的query很大,达到了1000000,所以离线算法空间上比较虚,
然而只会离线的.....于是把int改成short int险过....
#include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<iostream> #include<algorithm> #include<vector> #include<map> #include<queue> #include<stack> #include<string> #include<map> #include<set> #define eps 1e-6 #define LL long long using namespace std; //#pragma comment(linker, "/STACK:1024000000,1024000000") const int maxn = 10005; //const int INF = 0x3f3f3f3f; int dist[maxn], pnt[maxn], ans[1000005], forest[maxn]; bool vis[maxn]; vector<int> G[maxn], w[maxn], num[maxn]; vector<short int> query[maxn]; int n, m, c; int find(int x) { if(x == pnt[x]) return x; return pnt[x] = find(pnt[x]); } int find2(int x) { if(x == forest[x]) return x; return forest[x] = find2(forest[x]); } void dfs(int u, int val) { dist[u] = val; vis[u] = 1; pnt[u] = u; int sz1 = G[u].size(); for(int i = 0; i < sz1; i++) { int v = G[u][i]; if(vis[v]) continue; dfs(v, val+w[u][i]); pnt[v] = u; } int sz2 = query[u].size(); for(int i = 0; i < sz2; i++) { int v = query[u][i]; if(vis[v]) ans[num[u][i]] = dist[u] + dist[v] - 2*dist[find(v)]; } } void init() { memset(vis, 0, sizeof(vis)); for(int i = 1; i <= n; i++) { G[i].clear(); w[i].clear(); query[i].clear(); num[i].clear(); forest[i] = i; } } int main() { // freopen("input.txt", "r", stdin); while(scanf("%d%d%d", &n, &m, &c) == 3) { init(); for(int i = 0; i < m; i++) { int u, v, d; scanf("%d%d%d", &u, &v, &d); // cout << find2(u) << " " << find2(v) << endl; forest[find2(u)] = find2(v); // cout << find2(u) << " " << find2(v) << endl; G[u].push_back(v); G[v].push_back(u); w[u].push_back(d); w[v].push_back(d); } for(int i = 0; i < c; i++) { int u, v; scanf("%d%d", &u, &v); if(find2(u) != find2(v)) { // cout << find2(u) << " " << find2(v) << endl; ans[i] = -1; continue; } query[u].push_back(v); query[v].push_back(u); num[u].push_back(i); num[v].push_back(i); } for(int i = 1; i <= n; i++) if(!vis[i]) dfs(i, 0); // for(int i = 0; i < c; i++) cout << ans[i] << endl; for(int i = 0; i < c; i++) if(ans[i] == -1) printf("Not connected\n"); else printf("%d\n", ans[i]); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-27 06:06:50