Ural 1471. Tree
来源:互联网 发布:什么时候开始有的网络 编辑:程序博客网 时间:2024/05/28 14:56
LCA问题,这篇文章讲得不错:
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=lowestCommonAncestor
注意事项在代码中
#include<cstdio>#include<iostream>#include<cstring>#include<algorithm>using namespace std;#define N 110000#define MAX 55000int T[MAX];int P[MAX][50];int L[MAX];int W[MAX];int R[MAX][50];struct Node{ int v; int val; Node * next;}*head[N],tree[N];int ptr;int n;int sum;void add(int x,int y,int w){ tree[ptr].val=w; tree[ptr].v=y; tree[ptr].next=head[x]; head[x]=&tree[ptr++]; tree[ptr].val=w; tree[ptr].v=x; tree[ptr].next=head[y]; head[y]=&tree[ptr++];}void dfs(int rt,int par,int lv){ Node *p=head[rt]; while(p!=NULL) { if(p->v!=par) { L[p->v]=lv+1; T[p->v]=rt; W[p->v]=p->val; dfs(p->v,rt,lv+1); } p=p->next; }}void process(){ for(int i=0;i<n;i++) for(int j=0;1<<j<n;j++) { P[i][j]=-1; R[i][j]=0; } for(int i=0;i<n;i++) { P[i][0]=T[i]; R[i][0]=W[i]; } for(int j=1;1<<j<n;j++) for(int i=0;i<n;i++) if(P[i][j-1]!=-1) { P[i][j]=P[P[i][j-1]][j-1]; R[i][j]=R[i][j-1]+R[P[i][j-1]][j-1];//是R[P[i][j-1][j-1]不是R[R[i][j-1]][j-1] }}int query(int x,int y){ int sum=0; int tmp,log; if(L[x]<L[y]) tmp=x,x=y,y=tmp; for(log=1;1<<log<=L[x];log++); log--; for(int i=log;i>=0;i--) if(L[x]-(1<<i)>=L[y]) { sum+=R[x][i]; x=P[x][i]; } if(x==y)return sum; for(int i=log;i>=0;i--) { if(P[x][i]!=-1&&P[x][i]!=P[y][i])//不能相等,否则可能不是最近的公共祖先 { sum+=R[x][i]+R[y][i]; x=P[x][i]; y=P[y][i]; } } sum+=W[x]+W[y];//记得加上 return sum;}int main(){ scanf("%d",&n); int x,y,w; ptr=1; memset(head,NULL,sizeof(head)); for(int i=1;i<n;i++) { scanf("%d%d%d",&x,&y,&w); add(x,y,w); } dfs(0,0,1); L[0]=1; process(); int m; scanf("%d",&m); int g; for(int i=0;i<m;i++) { scanf("%d%d",&x,&y); printf("%d\n",query(x,y)); } return 0;}
- Ural 1471. Tree
- Ural 1471. Tree
- Ural Tree
- URAL 1022. Genealogical tree
- ural 1022 Genealogical Tree
- ural 1022. Genealogical Tree
- ural 1471 Tree题解
- Ural 1282. Game Tree
- ural 1752 Tree 2
- Ural 1471 Tree
- URAL 1022 Genealogical Tree
- URAL 1022. Genealogical Tree
- URAL 1282 Game Tree
- Binary Apple Tree URAL
- ural 1018 binary apple tree
- ural 1018 Binary Apple Tree
- URAL 1018 Binary Apple Tree
- ural 1108 Binary Apple Tree
- 获取文件属性的一些函数和结构体
- Noi2001 食物链
- Web分层设计研究(一)
- android Activity类中的finish()、onDestory()和System.exit(0) 三者的区别
- SVN简介
- Ural 1471. Tree
- 2013-10-29 实验之数组中元素全排列(递归思想题)
- MonetDB资料2
- w3school JS测验
- 查看oracle连接数
- 非常适合新手的长尾关键词挖掘方法
- hadoop2.0 遇到的问题 (持续更新)
- VCDebug、Ollydbg、WinDbg字符串条件断点设置方法总结
- 百度云推送客户端配置IOs