zoukankan      html  css  js  c++  java
  • P3379 【模板】最近公共祖先(LCA)

    我昨天晚上一个题目都没有做。。所以只有以前的tarjan代码了。。

     1 #include<set>
     2 #include<map>
     3 #include<list>
     4 #include<queue>
     5 #include<stack>
     6 #include<string>
     7 #include<cmath>
     8 #include<ctime>
     9 #include<vector>
    10 #include<bitset>
    11 #include<memory>
    12 #include<utility>
    13 #include<cstdio>
    14 #include<sstream>
    15 #include<iostream>
    16 #include<cstdlib>
    17 #include<cstring>
    18 #include<algorithm>
    19 using namespace std;
    20 
    21 int n,m,s,e,q,a,b;
    22 int fir[500050],to[1000100],ne[1001000];
    23 int firp[500500],as[1000050],nep[1001000],ans[1000100];
    24 bool vis[500050];
    25 int fa[500050];
    26 int f[500010];
    27 
    28 void add1(int u,int v){
    29     e++;
    30     to[e]=v;
    31     ne[e]=fir[u];
    32     fir[u]=e;
    33 }
    34 
    35 void add2(int x,int y){
    36     q++;
    37     as[q]=y;
    38     nep[q]=firp[x];
    39     firp[x]=q;
    40 }
    41 
    42 int findr(int x){
    43     if(x!=fa[x]){
    44         fa[x]=findr(fa[x]);
    45     }
    46     return fa[x];
    47 }
    48 
    49 void un(int x,int y){
    50     int xx=findr(x);
    51     int yy=findr(y);
    52     if(xx!=yy){
    53         fa[xx]=yy;
    54     }
    55 }
    56 
    57 void tarjan(int x){
    58     for(int i=fir[x];i;i=ne[i]){
    59         int t=to[i];
    60         if(t==f[x]){
    61             continue;
    62         }
    63         f[t]=x;
    64         tarjan(t);
    65         un(t,x);
    66         vis[t]=1;
    67     }
    68     for(int i=firp[x];i;i=nep[i]){
    69         int y=as[i]; 
    70         if(vis[y]) {
    71             ans[i]=findr(y);
    72         }
    73     }
    74 }
    75 
    76 int main(){
    77     scanf("%d%d%d",&n,&m,&s);
    78     for(int i=1;i<=n-1;i++){
    79         scanf("%d%d",&a,&b);
    80         add1(a,b);
    81         add1(b,a);
    82     }
    83     for(int i=1;i<=m;i++){
    84         scanf("%d%d",&a,&b);
    85         add2(a,b);
    86         add2(b,a);
    87     }
    88     for(int i=1;i<=n;i++){
    89         fa[i]=i;
    90         f[i]=i;
    91     }
    92     tarjan(s);
    93     for(int i=1;i<=m;i++){
    94         printf("%d
    ",max(ans[2*i],ans[2*i-1]));
    95     }
    96     return 0;
    97 }
  • 相关阅读:
    swift学习二:基本的语法
    Unity3D游戏开发之开发游戏带来的问题
    Linux makefile 教程 很具体,且易懂
    匈牙利算法
    ExtJs自学教程(1):一切从API開始
    rman
    微软历史最高市值是多少?
    安装Oracle JDK 7.0与8.0 for Mac OS X后Eclipse启动报错的解决之道
    linux-sfdisk 使用方法
    未将对象引用设置到对象的实例--可能出现的问题总结
  • 原文地址:https://www.cnblogs.com/hahaha2124652975/p/11231061.html
Copyright © 2011-2022 走看看