Bzoj 1787 ahoi 2008 meet emergency set doubling LCA

Source: Internet
Author: User

Give a tree, search for three vertices on the top, and ask the distance and shortest between the three vertices.


Train of Thought: it can be proved that this store must be two LCA points between the three points, and then enumeration is enough.



Code:

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define MAX 1000010#define INF 0x3f3f3f3fusing namespace std;int points,asks;int head[MAX],total;int next[MAX],aim[MAX];int deep[MAX],father[MAX][20];int length[MAX];inline void Add(int x,int y){next[++total] = head[x];aim[total] = y;head[x] = total;}void DFS(int x,int last){deep[x] = deep[last] + 1;length[x] = length[last] + 1; for(int i = head[x]; i; i = next[i]) {if(aim[i] == last)continue;father[aim[i]][0] = x;DFS(aim[i],x);}}void SparseTable(){for(int j = 1; j < 20; ++j)for(int i = 1; i <= points; ++i)father[i][j] = father[father[i][j - 1]][j - 1];}inline int GetLCA(int x,int y){if(deep[x] < deep[y])swap(x,y);for(int i = 19; ~i; --i)if(deep[father[x][i]] >= deep[y])x = father[x][i];if(x == y)return x;for(int i = 19; ~i; --i)if(father[x][i] != father[y][i])x = father[x][i],y = father[y][i];return father[x][0];}inline int GetLength(int x,int y,int lca){return length[x] + length[y] - (length[lca] << 1);}int main(){cin >> points >> asks;for(int x,y,i = 1; i < points; ++i) {scanf("%d%d",&x,&y);Add(x,y),Add(y,x);}DFS(1,0);SparseTable();for(int x,y,z,i = 1; i <= asks; ++i) {scanf("%d%d%d",&x,&y,&z);int lca = GetLCA(x,y),ans = INF,p = 0;int temp = GetLength(x,y,lca) + GetLength(z,lca,GetLCA(z,lca));if(temp < ans)ans = temp,p = lca;lca = GetLCA(y,z);temp = GetLength(y,z,lca) + GetLength(x,lca,GetLCA(x,lca));if(temp < ans)ans = temp,p = lca;lca = GetLCA(x,z);temp = GetLength(x,z,lca) + GetLength(y,lca,GetLCA(y,lca));if(temp < ans)ans = temp,p = lca;printf("%d %d\n",p,ans);}return 0;}


Bzoj 1787 ahoi 2008 meet emergency set doubling LCA

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.