[题目链接]
https://www.lydsy.com/JudgeOnline/problem.php?id=3362
[算法]
带权并查集
时间复杂度 : O(NlogN)
[代码]
#include<bits/stdc++.h>using namespace std;const int MAXN = 400010;struct Que{ ???????int f1 , f2 , t; ???????int id;} que[MAXN];int n , m;int f[MAXN] , dist[MAXN] , x[MAXN] , y[MAXN] , X[MAXN] , Y[MAXN] , d[MAXN];int ans[MAXN];char dir[MAXN][10];template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); }template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); }template <typename T> inline void read(T &x){ ???T f = 1; x = 0; ???char c = getchar(); ???for (; !isdigit(c); c = getchar()) if (c == ‘-‘) f = -f; ???for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - ‘0‘; ???x *= f;}inline bool cmp(Que a,Que b){ ???????return a.t < b.t;}inline int get_root(int x){ ???????if (f[x] == x) return x; ???????int fa = get_root(f[x]); ???????X[x] += X[f[x]]; ???????Y[x] += Y[f[x]]; ???????return f[x] = fa; ???????}int main(){ ???????????????scanf("%d%d",&n,&m); ???????for (int i = 1; i <= n; i++) f[i] = i; ???????for (int i = 1; i <= m; i++) scanf("%d%d%d%s",&x[i],&y[i],&d[i],&dir[i]); ???????int q; ???????read(q); ???????for (int i = 1; i <= q; i++) ????????{ ???????????????scanf("%d%d%d",&que[i].f1 , &que[i].f2 , &que[i].t); ???????????????que[i].id = i; ???????} ???????????sort(que + 1,que + q + 1,cmp); ???????int cur = 1; ???????for (int i = 1; i <= q; i++) ???????{ ???????????????while (cur <= que[i].t) ???????????????{ ???????????????????????int sx = get_root(x[cur]) , sy = get_root(y[cur]); ???????????????????????if (sx == sy) continue; ???????????????????????f[sx] = sy; ???????????????????????if (dir[cur][0] == ‘E‘) ???????????????????????{ ???????????????????????????????X[sx] = -X[x[cur]] + X[y[cur]] - d[cur]; ???????????????????????????????Y[sx] = -Y[x[cur]] + Y[y[cur]]; ???????????????????????} ???????????????????????if ( dir[cur][0] == ‘W‘ ) ???????????????????????{ ???????????????????????????????X[sx] = -X[x[cur]] + X[y[cur]] + d[cur]; ???????????????????????????????Y[sx] = -Y[x[cur]] + Y[y[cur]]; ???????????????????????} ????????????????????????if (dir[cur][0] == ‘N‘) ?????????????????????{ ???????????????????????????????Y[sx] = -Y[x[cur]] + Y[y[cur]] - d[cur]; ???????????????????????????????X[sx] = -X[x[cur]] + X[y[cur]] ; ????????????????????} ????????????????????if (dir[cur][0] == ‘S‘) ????????????????????{ ???????????????????????????????Y[sx] = -Y[x[cur]] + Y[y[cur]] + d[cur]; ???????????????????????????????X[sx] = -X[x[cur]] + X[y[cur]]; ???????????????????????} ???????????????????????++cur; ???????????????????} ???????????????????????if (get_root(que[i].f1) != get_root(que[i].f2)) ans[que[i].id] = -1; ???????????????else ans[que[i].id] = abs(X[que[i].f1] - X[que[i].f2]) + abs(Y[que[i].f1] - Y[que[i].f2]); ???????} ???????for (int i = 1; i <= q; i++) printf("%d\n",ans[i]); ???????????????return 0; ???}
[USACO 2004DEC] Navigation Nightmare
原文地址:https://www.cnblogs.com/evenbao/p/9807593.html