【ZOJ3195】Design the City-LCA算法
来源:互联网 发布:武汉淘宝大学官网 编辑:程序博客网 时间:2024/05/16 08:24
题目大意:有一座城市有N个区域(从0开始编号),每两个区域之间有且只有一条路径相连,有Q个询问,每个询问包含三个整数x,y,z,意为询问连接x,y,z三点的最短路径长度。对于每个询问,给出正确的答案。
做法:在模板上进行了一些加强,但是也不难,容易得出:连接x,y,z三点的最短路径长度等于x和y,y和z,x和z之间的路径长度之和/2。由于点是从0编号,所以在处理时要注意一些细节,其他的就不是很难了。
以下是本人代码(由于ZOJ不可用,自己用几个极限数据测了一下,应该是正确的):
#include <cstdio>#include <cstdlib>#include <cstring>#include <iostream>#include <algorithm>using namespace std;int n,a,b,tot,Q,first[50010],f[50010],fa[50010],dis[50010],root;int firstq[70010],ans[70010];bool vis[50010];struct {int v,d,next;} e[100010];struct {int v,pos,next;} q[420010];void insert(int a,int b,int c){ e[++tot].v=b; e[tot].d=c; e[tot].next=first[a]; first[a]=tot;}void insertq(int a,int b,int i){ q[++tot].v=b; q[tot].pos=i; q[tot].next=firstq[a]; firstq[a]=tot;}int find(int x){ int r=x,i=x,j; while(r!=f[r]) r=f[r]; while(i!=r) {j=f[i];f[i]=r;i=j;} return r;}void merge(int a,int b){ f[find(a)]=find(b);}void tarjan(int v){ f[v]=v; for(int i=first[v];i;i=e[i].next) if (e[i].v!=fa[v]){ fa[e[i].v]=v; dis[e[i].v]=dis[v]+e[i].d; tarjan(e[i].v);} vis[v]=1; for(int i=firstq[v];i;i=q[i].next) if (vis[q[i].v]) ans[q[i].pos]+=dis[v]+dis[q[i].v]-2*dis[find(q[i].v)]; if (fa[v]!=-1) merge(v,fa[v]);}int main(){ bool flag=0; while(scanf("%d",&n)!=EOF) {memset(first,0,sizeof(first));memset(firstq,0,sizeof(firstq));memset(vis,0,sizeof(vis));memset(ans,0,sizeof(ans));if (flag) printf("\n");flag=1;for(int i=0;i<n;i++) fa[i]=-1;tot=0;for(int i=1;i<n;i++){ int a,b,c; scanf("%d%d%d",&a,&b,&c); insert(a,b,c);insert(b,a,c);}scanf("%d",&Q);tot=0;for(int i=1;i<=Q;i++){ int a,b,c; scanf("%d%d%d",&a,&b,&c); insertq(a,b,i);insertq(b,a,i); insertq(b,c,i);insertq(c,b,i); insertq(a,c,i);insertq(c,a,i);}dis[0]=0;tarjan(0);for(int i=1;i<=Q;i++) printf("%d\n",ans[i]/2); } return 0;}
0 0
- 【ZOJ3195】Design the City-LCA算法
- ZOJ3195 Design the city
- 3195 Design the city //LCA
- ZOJ 3195 - Design the city(LCA'离线算法Tarjan)
- 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变形)
- zoj 3195 Design the city 【LCA转RMQ】 【求三点最短距离】
- ZOJ 题目3195 Design the city(LCA+RMQ)
- ZOJ 3195 Design the city LCA转RMQ在线
- 从苏宁电器到卡巴斯基第26篇:难忘的三年硕士时光 IV
- uva12171 sculpture 离散化 3维bfs求面积体积
- ZooKeeper集群搭建详细步骤
- 过滤Servlet--过滤器
- LeetCode | Valid Number
- 【ZOJ3195】Design the City-LCA算法
- Qt QMediaPlayer(铺满整个窗口)
- Magic c++ 一个好的可视化Linux开发工具
- uva12166 修改天平 元素的贡献值-最优解
- 一个巧妙地方式改变input的默认样式
- go1.6.2 strings.Split()我觉得有些问题
- Java虚拟机类加载机制---深入理解Java虚拟机
- Android 使用Android Studio + Gradle 或 命令行 进行apk签名打包
- uva11882 最大的数 bfs 遍历估价剪枝