模板攒起来
#include <iostream> #include <algorithm> #include <cstdlib> #include <cstdio> #include <cstring> #include <queue> #include <stack> #pragma comment(linker, "/STACK:1024000000"); #define LL long long int using namespace std; const int MAXN = 10010; const int MAXM = 10010; struct N { int v,w,next; }edge[MAXM*2]; int Top; int head[MAXN]; int MAXSIZE; int dep[MAXN]; int seq[MAXN*2]; int R[MAXN]; struct ST { int dep,point; bool operator < (const ST &A) const { return dep < A.dep; } }st[MAXN*8]; void Link(int u,int v,int w) { edge[Top].v = v; edge[Top].w = w; edge[Top].next = head[u]; head[u] = Top++; } void Init() { memset(head,-1,sizeof(head)); Top = 0; MAXSIZE = 0; } void InitDep(int s,int pre = -1,int d = 0) { R[s] = ++MAXSIZE; seq[MAXSIZE] = s; dep[s] = d; for(int p = head[s]; p != -1; p = edge[p].next) { if(edge[p].v != pre) { InitDep(edge[p].v,s,d+edge[p].w); seq[++MAXSIZE] = s; } } } void InitST(int site,int l,int r) { if(l == r) { st[site].dep = dep[seq[l]]; st[site].point = seq[l]; return ; } int mid = (l+r)>>1; InitST(site<<1,l,mid); InitST(site<<1|1,mid+1,r); st[site] = st[site<<1].dep < st[site<<1|1].dep ? st[site<<1] : st[site<<1|1]; } ST QueryLCA(int site,int L,int R,int l,int r) { if(L == l && R == r) return st[site]; int mid = (L+R)>>1; if(r <= mid) return QueryLCA(site<<1,L,mid,l,r); else if(mid < l) return QueryLCA(site<<1|1,mid+1,R,l,r); return min(QueryLCA(site<<1,L,mid,l,mid),QueryLCA(site<<1|1,mid+1,R,mid+1,r)); } int fa[MAXN]; int Find(int x) { int t = x,f; while(t != fa[t]) t = fa[t]; while(x != fa[x]) f = fa[x],fa[x] = t,x = f; return x; } int main() { int n,m,c; int u,v,w; int i,l,r; ST LCA; while(scanf("%d %d %d",&n,&m,&c) != EOF) { Init(); for(i = 1;i <= n; ++i) fa[i] = i; while(m--) { scanf("%d %d %d",&u,&v,&w); Link(u,v,w); Link(v,u,w); fa[Find(u)] = Find(v); } for(i = 1;i <= n; ++i) if(fa[i] == i) Link(0,i,0),Link(i,0,0); InitDep(0); InitST(1,1,MAXSIZE); while(c--) { scanf("%d %d",&u,&v); if(Find(u) != Find(v)) { puts("Not connected"); continue; } l = min(R[u],R[v]); r = max(R[u],R[v]); LCA = QueryLCA(1,1,MAXSIZE,l,r); printf("%d\n",dep[u]+dep[v]-dep[LCA.point]*2); } } return 0; }
时间: 2024-11-02 15:47:16