标签:str 乱序 span add turn max 复杂 cost 时间复杂度
学习了波Tarjan求LCA,感觉比倍增LCA麻烦啊。。。
时间复杂度是 O(N+Q) N是点的数量 Q是询问数量
因为回答是乱序的,所以还要排序。。Orz好麻烦
1 #include <cstring> 2 #include <algorithm> 3 #include <cstdio> 4 #include <cstdlib> 5 #include <vector> 6 using namespace std; 7 8 const int maxn=51005; 9 10 struct node{ 11 int u,v,w,next; 12 node(){} 13 node(int _u,int _v,int _w,int _next){ 14 u = _u; 15 v = _v; 16 w = _w; 17 next = _next; 18 } 19 }Edge[maxn<<1]; 20 21 typedef pair<int,int> P; 22 vector<P>Qes[77777]; 23 vector<P>ans; 24 25 bool vis[maxn]; 26 int fa[maxn],dis[maxn],head[maxn<<1]; 27 int n,m,x,y,z,Count; 28 29 void AddEdge(int u,int v,int w){ 30 Count++; 31 Edge[Count] = node(u,v,w,head[u]); 32 head[u]=Count; 33 } 34 35 inline int getfa(int x){ 36 if(x!=fa[x]) return fa[x] = getfa(fa[x]); 37 return x; 38 } 39 40 inline void un(int x,int y){ 41 int fx = getfa(x); 42 int fy = getfa(y); 43 if(fx==fy) return; 44 fa[fy]=fx; 45 } 46 47 void dfs(int x,int f,int cost){ 48 fa[x]=x; 49 dis[x]+=cost+dis[f]; 50 for(int i=head[x];i;i=Edge[i].next){ 51 int v = Edge[i].v; 52 if(v==f) continue; 53 dfs(v,x,Edge[i].w); 54 un(x,v); 55 fa[getfa(x)]=x; 56 } 57 vis[x]=1; 58 for(int i=0;i<Qes[x].size();i++){ 59 if(vis[Qes[x][i].second]){ 60 int father = fa[getfa(Qes[x][i].second)]; 61 ans.push_back(P(Qes[x][i].first,dis[x]+dis[Qes[x][i].second]-2*dis[father])); 62 } 63 } 64 65 } 66 67 int main(){ 68 scanf("%d",&n); 69 for(int i=1;i<=n;i++) fa[i]=i; 70 for(int i=1;i<n;i++){ 71 scanf("%d%d%d",&x,&y,&z); 72 AddEdge(x,y,z); 73 AddEdge(y,x,z); 74 } 75 scanf("%d",&m); 76 for(int i=0;i<m;i++){ 77 scanf("%d%d",&x,&y); 78 Qes[x].push_back(P(i,y)); 79 Qes[y].push_back(P(i,x)); 80 } 81 dfs(1,-1,0); 82 sort(ans.begin(),ans.end()); 83 for(int i=0;i<ans.size();i++){ 84 printf("%d\n",ans[i].second); 85 } 86 return 0; 87 }
标签:str 乱序 span add turn max 复杂 cost 时间复杂度
原文地址:http://www.cnblogs.com/OIerLYF/p/7496085.html