poj 1470 LCA公共祖先次数
来源:互联网 发布:创业创业软件股票行情 编辑:程序博客网 时间:2024/05/17 06:25
题意:给你树的信息,m次询问公共祖先,输出被作为祖先的次数
解法:LCA离线算法Tarjan+并查集
代码
- /*************************************************************************
- > File Name: poj1470.cpp
- > Author: cy
- > Mail: 1002@qq.com
- > Created Time: 14/11/9 14:50:27
- ************************************************************************/
- #include<iostream>
- #include<cstring>
- #include <algorithm>
- #include<cstdlib>
- #include<vector>
- #include<cmath>
- #include<stdlib.h>
- #include<iomanip>
- #include<list>
- #include<deque>
- #include<map>
- #include <stdio.h>
- #include <queue>
- const int maxn=1000+5;
- #define inf 0x3f3f3f3f
- #define INF 0x3FFFFFFFFFFFFFFFLL
- #define rep(i,n) for(i=0;i<n;i++)
- #define reP(i,n) for(i=1;i<=n;i++)
- #define ull unsigned long long
- #define ll long long
- #define cle(a) memset(a,0,sizeof(a))
- using namespace std;
- int head[maxn],used[maxn],fat[maxn],cnt[maxn],flag[maxn],Num_edge;
- int m;
- int x[maxn*maxn],y[maxn*maxn];
- struct Edge{
- int to,next;
- }edge[maxn*maxn];
- void add_edge(int a,int b){
- edge[Num_edge].to=b;edge[Num_edge].next=head[a];head[a]=Num_edge++;
- edge[Num_edge].to=a;edge[Num_edge].next=head[b];head[b]=Num_edge++;
- }
- void init()
- {
- memset(head,-1,sizeof(head));
- cle(used);cle(cnt);cle(flag);
- Num_edge=0;
- }
- int get_fat(int x){
- if(x==fat[x])return fat[x];
- else return fat[x]=get_fat(fat[x]);
- }
- void Tarjan(int k){
- used[k]=1;
- fat[k]=k;
- int i;
- rep(i,m){
- if(x[i]==k&&used[y[i]])cnt[get_fat(y[i])]++;
- if(y[i]==k&&used[x[i]])cnt[get_fat(x[i])]++;
- }
- for(i=head[k];i!=-1;i=edge[i].next)
- {
- int to=edge[i].to;
- if(!used[to]){
- Tarjan(to);
- fat[to]=k;
- }
- }
- }
- char str11[2],str22[2];
- int main()
- {
- #ifndef ONLINE_JUDGE
- freopen("in.txt","r",stdin);
- //freopen("out.txt","w",stdout);
- #endif
- int n;
- while(cin>>n){
- init();
- int a,b,t;
- int i,j;
- rep(i,n){
- scanf("%d%1s%1s%d%1s",&a,&str11,&str11,&t,&str22);
- rep(j,t){
- scanf("%d",&b);
- add_edge(a,b);
- flag[b]++;
- }
- }
- cin>>m;
- rep(i,m){
- scanf("%1s%d %d%1s",&str11,&a,&b,&str22);
- x[i]=a;y[i]=b;
- }
- for(i=1;i<=n;i++){
- if(flag[i]==0){
- break;
- }
- }
- Tarjan(i);
- for(i=1;i<=n;i++){
- if(cnt[i]){
- printf("%d:%d\\n",i,cnt[i]);
- }
- }
- }
- return 0;
- }
0 0
- poj 1470 LCA公共祖先次数
- POJ 1470 LCA 公共祖先
- POJ 1470 Closest Common Ancestors【最近公共祖先LCA】
- poj 3694 Network LCA最小公共祖先
- poj 1330 LCA最近公共祖先
- poj 1330 LCA 最近公共祖先
- poj 1986 最近公共祖先 (lca 倍增)
- lca最小公共祖先祖先
- 最近公共祖先LCA
- 最近公共祖先(LCA)
- Lca 最近公共祖先
- LCA----最近公共祖先
- LCA (最近公共祖先)
- LCA最近公共祖先
- LCA 最近公共祖先
- 最近公共祖先 LCA
- LCA--最近公共祖先
- LCA(最近公共祖先)
- 小白系列-免费广告路由器web认证设置(1)
- HDU 1285 确定比赛名次
- 新驻入CSDN博客
- ssl流程
- 27_加载大图片到内存
- poj 1470 LCA公共祖先次数
- /proc目录
- 米聊营销软件 一键修改资料 站街 自动换IP 11月7号更新
- vs2010快捷键大全
- 驾校考试科目二完整流程
- Android 手势介绍 开发图片浏览
- poj2373 Dividing the Path 单调队列dp
- “码农”是IT从业者一个自嘲的称号
- Java对象的创建,布局,访问