您的位置:首页 > 其它

BZOJ 1787: [Ahoi2008]Meet 紧急集合

2015-12-29 20:44 471 查看
这道题不难,就是3个点的lca。算法有点多,写成树链剖分的吧!跑完2400多毫秒。还好,挺顺利的,加油!努力啊!注意看数据范围!相信自己,能行的

#include<cstdio>
#include<iostream>
#include<cstring>
#define rep(i,j,k) for(int i = j; i <= k; i++)
#define down(i,j,k) for(int i = j; i >= k; i--)
#define maxn 500005
using namespace std;

struct edge{
int to; edge* next;
};
edge* head[500005], *pt, edges[1000005];

void add_edge(int x,int y)
{
pt->to = x, pt->next = head[y], head[y] = pt++;
pt->to = y, pt->next = head[x], head[x] = pt++;
}

inline int read()
{
int s = 0, t = 1; char c = getchar();
while( !isdigit(c) ){
if( c == '-' ) t = -1; c = getchar();
}
while( isdigit(c) ){
s = s * 10 + c - '0'; c = getchar();
}
return s * t;
}

int top[maxn], dep[maxn], pa[maxn], size[maxn], son[maxn];

void dfs(int now)
{
son[now] = 0, size[now] = 1;
for(edge*i = head[now]; i; i=i->next){
int to = i->to; if( to == pa[now] ) continue;
pa[to] = now, dep[to] = dep[now] + 1;
dfs(to);
if( size[to] > size[son[now]] ) son[now] = to;
}
}

void dfs2(int now,int ph)
{
top[now] = ph;
if( son[now] ) dfs2(son[now],ph);
for(edge*i = head[now]; i; i=i->next){
int to = i->to; if( to == pa[now] || to == son[now] ) continue;
dfs2(to,to);
}
}

int lca(int x,int y)
{
while( top[x] != top[y] ){
if( dep[top[x]] < dep[top[y]] ) swap(x,y);
x = pa[top[x]];
}
if(dep[x] < dep[y] ) return x;
else return y;
}

int main()
{
int n = read(), m = read(); pt = edges;
rep(i,1,n-1){
int x = read(), y = read();
add_edge(x,y);
}
dep[1] = 0; dfs(1); dfs2(1,1);
rep(i,1,m){
int x = read(), y = read(), z = read();
int lc1 = lca(x,y), lc2 = lca(y,z), lc3 = lca(x,z);
if( lc1 == lc2 ){
printf("%d %d\n",lc3,dep[y]-dep[lc1]+dep[x]-dep[lc1]+dep[z]-dep[lc3]);
}
else if( lc2 == lc3 ){
printf("%d %d\n", lc1,dep[z]-dep[lc2]+dep[y]-dep[lc2]+dep[x]-dep[lc1]);
}
else if( lc1 == lc3 ){
printf("%d %d\n", lc2,dep[x]-dep[lc1]+dep[y]-dep[lc1]+dep[z]-dep[lc2]);
}
}
return 0;
}


1787: [Ahoi2008]Meet 紧急集合

Time Limit: 20 Sec Memory Limit: 162 MB
Submit: 1829 Solved: 846
[Submit][Status][Discuss]

Description



Input



Output



Sample Input

6 4

1 2

2 3

2 4

4 5

5 6

4 5 6

6 3 1

2 4 4

6 6 6

Sample Output

5 2

2 5

4 1

6 0

HINT



Source

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: