zoj 3195 Design the city(LCA)
来源:互联网 发布:mac如何打#键 编辑:程序博客网 时间:2024/05/22 13:35
zoj 3195 Design the city
树上三点最短距离,分别求两点间最短距离,再求和除以2
#include<cstdio>#include<cstring>#include<vector>using namespace std;#define MAXN 50005#define MAXM 70005struct tnode{ int v,d; tnode(int v=0,int d=0):v(v),d(d){}};struct qnode{ int v,id; qnode(int v=0,int id=0):v(v),id(id){}};vector<tnode> t[MAXN];vector<qnode> q[MAXN];int ans[MAXM],fa[MAXN],dis[MAXN];bool vis[MAXN];int n,m;void ini(){ for(int i=0;i<n;i++) { t[i].clear(); q[i].clear(); vis[i]=false; fa[i]=i; }}int find(int x) {return x==fa[x]?x:fa[x]=find(fa[x]);}void lca(int u){ vis[u]=true; for(int i=0;i<q[u].size();i++) { int v=q[u][i].v; if(vis[v]) ans[q[u][i].id]+=dis[u]+dis[v]-2*dis[find(v)]; } for(int i=0;i<t[u].size();i++) { int v=t[u][i].v; if(!vis[v]) { dis[v]=dis[u]+t[u][i].d; lca(v); fa[v]=u; } }}int main(){ bool flag=false; while(scanf("%d",&n)!=EOF) { if(flag) printf("\n"); else flag=true; ini(); int u,v,d; for(int i=0;i<n-1;i++) { scanf("%d%d%d",&u,&v,&d); t[u].push_back(tnode(v,d)); t[v].push_back(tnode(u,d)); } scanf("%d",&m); for(int i=0;i<m;i++) { scanf("%d%d%d",&u,&v,&d); ans[i]=0; q[u].push_back(qnode(v,i)); q[v].push_back(qnode(u,i)); q[u].push_back(qnode(d,i)); q[d].push_back(qnode(u,i)); q[v].push_back(qnode(d,i)); q[d].push_back(qnode(v,i)); } dis[1]=0; lca(1); for(int i=0;i<m;i++) printf("%d\n",ans[i]/2); } return 0;}
0 0
- zoj 3195 Design the city LCA
- zoj 3195 Design the city (LCA)
- Design the city - ZOJ 3195 LCA
- zoj 3195 Design the city(LCA)
- ZOJ - 3195 Design the city(LCA)
- ZOJ 3195Design the city LCA
- ZOJ 3195 Design the city LCA转RMQ
- ZOJ 3195 Design the city (在线LCA,4级)
- ZOJ Problem Set - 3195 Design the city 【Tarjan离线LCA】
- ZOJ 3195 - Design the city(LCA'离线算法Tarjan)
- ZOJ 3195 Design the city(LCA Tarjan)
- ZOJ 3195 Design the city(LCA变形)
- zoj 3195 Design the city 【LCA转RMQ】 【求三点最短距离】
- ZOJ 题目3195 Design the city(LCA+RMQ)
- ZOJ 3195 Design the city LCA转RMQ在线
- 3195 Design the city //LCA
- Zoj 3195 Design the city
- ZOJ 3195 Design the city
- 第八周项目 4 个人所得税计算机
- yaml格式小问题
- hdu 5012 Dice 2014 ACM/ICPC Asia Regional Xi'an Online
- 作价超40亿,苏宁缺钱卖店还是另辟新径?
- Linux实验二【最简单kernel module的例子】
- zoj 3195 Design the city(LCA)
- C++浮点数比较
- 第八周 项目四 用if~else多分段函数求值
- 初探 iOS8 中的 Size Class
- FZU 2089 数字游戏
- 数据结构上机实验 一元多项式的加和乘实验2
- C#创建xml文件的问题
- 2-10. 海盗分赃(25)
- 阿弗莱克见面拿空间罚款了