倍增
#include#include using namespace std;int du[99999];int flag[2999];double dis[2099];int w[2989][2999];int n,m;int main(){ int x,y,z; scanf("%d%d",&n,&m); memset(dis,127,sizeof(dis)); for(int i=1;i<=m;i++) { scanf("%d%d%d",&x,&y,&z); w[x][y]=100-z; w[y][x]=100-z; } scanf("%d%d",&x,&y); int head=0,tail=1; du[1]=y; flag[y]=1; dis[y]=100; do { head++; int t=du[head]; flag[t]=0; for(int i=1;i<=n;i++) if(w[t][i]) { if(dis[i]>dis[t]/(w[t][i])*100) { dis[i]=dis[t]/(w[t][i])*100; if(!flag[i]) { du[++tail]=i; flag[i]=1; } } } }while(head
#include#include using namespace std;int fat[500800][20];int deep[505000];int tot;int num[1099999];int nxt[1099999];int head[509999];int n,m;inline int Read(){ int x=0,f=1;char c=getchar(); while(c>'9'||c<'0') { if(c=='-') f=-1;c=getchar();} while(c>='0'&&c<='9') {x=x*10+c-'0'; c=getchar();} return x*f;}void add(int x,int y){ num[++tot]=y; nxt[tot]=head[x]; head[x]=tot;}void dfs(int x){ for(int i=head[x];i;i=nxt[i]) { int t=num[i]; if(!fat[t][0]) { fat[t][0]=x; deep[t]=deep[x]+1; dfs(t); } } }void itin(){ for(int i=1;(1< <=n;i++) for(int j=1;j<=n;j++) if(fat[j][i-1]!=-1) fat[j][i]=fat[fat[j][i-1]][i-1];}int lca(int a,int b){ int i; int j; if(deep[a] =0;j--) if(deep[a]-(1< =deep[b]) a=fat[a][j]; if(a==b) return a; for(j=i;j>=0;j--) { if(fat[a][j]!=-1&&fat[a][j]!=fat[b][j]) { a=fat[a][j]; b=fat[b][j]; } } return fat[a][0];}int main(){ int s; scanf("%d%d",&n,&m); scanf("%d",&s); for(int j=1;j<=n-1;j++) { int x,y; x=Read(); y=Read(); add(x,y); add(y,x); } deep[s]=0; fat[s][0]=-1; dfs(s); itin(); int x,y; for(int i=1;i<=m;i++) { x=Read(); y=Read(); printf("%d\n",lca(x,y)); }}