LCA最近公共祖先(RMQ、Tarjan)

题目:http://poj.org/problem?id=1330

讲解:http://blog.csdn.net/tingyun_say/article/details/52092464

离线算法:dfs+并查集(Tarjan)

#include
#include
#include
#include
#include
using namespace std;
const int N=1e4+107;
const int inf=0x3f3f3f3f;
int n,q1,q2;
int f[N],a[N];
bool c[N],flag[N];
vector v[N];
int find(int k)
{
    if(f[k]==k) return k;
    f[k]=find(f[k]);
    return f[k];
}
int unions(int x,int y)
{
    int xx=find(x),yy=find(y);
    f[yy]=xx;
    return 0;
}
int tarjan(int u)
{
    for(int i=0;i
在线算法:dfs+RMQ(RMQ)
#include
#include
#include
#include
#include
using namespace std;
const int N=1e4+107;
const int inf=0x3f3f3f3f;
const int log=20;
int dp[N][log],depth[N],deg[N];
struct node{
    int to;
    node *next;
}g[2*N],*cur,*head[N];
void addnode(int u,int v)
{
    cur->to=v;
    cur->next=head[u];
    head[u]=cur++;
}
void dfs(int u)
{
    depth[u]=depth[dp[u][0]]+1;
    for(int i=1;inext) dfs(it->to);
}
int lca(int u,int v)
{
    if(depth[u]=0   ;i--,st>>=1)
        if(st<=depth[u]-depth[v]) u=dp[u][i];
    if(u==v) return u;
    for(int i=log-1;i>=0;i--)
        if(dp[v][i]!=dp[u][i])
        v=dp[v][i],u=dp[u][i];
    return dp[u][0];
}
void init(int n)
{
    for(int i=0;i<=n;i++)
    {
        dp[i][0]=0;
        head[i]=NULL;
        deg[i]=0;
    }
    cur=g;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,u,v;
        scanf("%d",&n);
        init(n);
        for(int i=0;i
HDU  2586
Lca
#define N 50005
vector mp[N],w[N],query[N],num[N];
int p[N],d[N],res[N];
bool vis[N];
int n;

void Init()
{
    int i;
    for(i=1;i<=n;i++)
    {
        mp[i].clear();
        w[i].clear();
        query[i].clear();
        num[i].clear();
        p[i]=i;
        d[i]=0;
        vis[i]=false;
    }
}

int Find(int x)
{
    if(p[x]!=x)
        p[x]=Find(p[x]);
    return p[x];
}

void Union(int x,int y)
{
    x=Find(x);
    y=Find(y);
    if(x!=y)
        p[y]=x;
}

void Tarjan(int cur,int v)
{
    int size,i,tmp;

    vis[cur]=true;
    d[cur]=v;
    size=mp[cur].size();
    for(i=0;i


你可能感兴趣的:(动态规划——经典题例,经典例题,ACM-ICPC,2016暑期特训1)