POJ - 1330 Nearest Common Ancestors tanjan_LCA
本站寻求有缘人接手,详细了解请联系站长QQ1493399855
传送门
题意就是题目
所谓在线,就是一个一个贼笨且时间太长。
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<set>
#include<stack>
#include<vector>
#include<map>
#include<queue>
#define myself i,l,r
#define lson i<<1
#define rson i<<1|1
#define Lson i<<1,l,mid
#define Rson i<<1|1,mid+1,r
#define half (l+r)/2
#define inff 0x3f3f3f3f
#define lowbit(x) x&(-x)
#define me(a,b) memset(a,b,sizeof(a))
#define min4(a,b,c,d) min(min(a,b),min(c,d))
#define min3(x,y,z) min(min(x,y),min(y,z))
typedef long long ll;
using namespace std;
const int maxn=1e4+5;
int f[maxn],vis[maxn];
int n;
int main()
{int x,y,t;scanf("%d",&t);while(t--){scanf("%d",&n);me(f,-1);me(vis,0);n--;while(n--){scanf("%d %d",&x,&y);f[y]=x;}scanf("%d %d",&x,&y);while(y!=-1){vis[y]=1;y=f[y];}while(!vis[x])x=f[x];printf("%d
",x);}return 0;
}
离线的话刚刚学了怎么用tanjan思想来解决,照着板子敲又t又wrong呢,不知道为啥
思想在这------>>>>>here!
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<set>
#include<stack>
#include<vector>
#include<map>
#include<queue>
#define myself i,l,r
#define lson i<<1
#define rson i<<1|1
#define Lson i<<1,l,mid
#define Rson i<<1|1,mid+1,r
#define half (l+r)/2
#define inff 0x3f3f3f3f
#define lowbit(x) x&(-x)
#define me(a,b) memset(a,b,sizeof(a))
#define min4(a,b,c,d) min(min(a,b),min(c,d))
#define min3(x,y,z) min(min(x,y),min(y,z))
typedef long long ll;
using namespace std;
const int maxn=1e4+5;
struct node
{int to,p;
}edge[maxn],qedge[maxn];
int vis[maxn],f[maxn],head[maxn],qhead[maxn],rd[maxn],ans;
int n,sign,qsign;
int find(int x)
{if(x==f[x])return x;elsereturn f[x]=find(f[x]);
}
void add(int u,int v)
{edge[sign]={v,head[u]};head[u]=sign++;
}
void qadd(int u,int v)
{qedge[qsign]={v,qhead[u]};qhead[u]=qsign++;
}
void init()
{sign=qsign=0;for(int i=1;i<=n;i++){qhead[i]=head[i]=-1;rd[i]=vis[i]=0;}
}
void dfs(int u)
{f[u]=u;vis[u]=1;for(int i=head[u];i!=-1;i=edge[i].p){int v=edge[i].to;if(!vis[v]){dfs(v);f[v]=u;}}for(int i=qhead[u];i!=-1;i=qedge[i].p){int v=qedge[i].to;if(vis[v]){ans=find(v);return ;}}
}
int main()
{int x,y,t;scanf("%d",&t);while(t--){scanf("%d",&n);init();for(int i=1;i<n;i++){scanf("%d %d",&x,&y);rd[y]=1;add(x,y);add(y,x);}scanf("%d %d",&x,&y);qadd(x,y);qadd(y,x);int i;for(i=1;i<=n;i++){if(rd[i]==0)break;}dfs(i);printf("%d
",ans);}return 0;
}