- 货车运输
- 2017-09-28 18:51:57 @
如果能帮忙查出错红包答谢
```cpp
#include<bits/stdc++.h>
using namespace std;
const int inf=0x7f7f7f7f;
inline int read() {
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9') {
if(ch=='-')f=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9') {
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
const int N=100005,M=500005;
int n,m,fa[N],cnt,head[N],erk[22],vis[N],dep[N];
int gf(int x) {return fa[x]=(fa[x]==x)?x:gf(fa[x]);}
struct note {int s,v,w;} e1[M];
struct edge {int next,v,w;} e[M*2];
bool cmp(note a,note b) {return a.w>b.w;}
struct ancestor {int num,miny;} anc[N][22];
void add(int x,int y,int z) { e[++cnt].v=y;e[cnt].w=z;e[cnt].next=head[x];head[x]=cnt;}
int getans(int x,int des) {
int ans=inf;
int dert=dep[x]-dep[des];
for(int i=0;i<=22;i++)
{
if(dert&(1<<i))
{
ans=min(ans,anc[x][i].miny);
x=anc[x][i].num;
}
}
/* for(int i=dert;i;i=i/2)
{
int temp=i&1;
if(temp) ans=min(ans,anc[x][temp].miny),x=anc[x][temp].num;
}
*/
// cout<<"fuck the :"<<ans<<endl;
return ans;
}
void dfs(int u) {
vis[u]=1;
for(int i=1;i<=22;i++)
{
if(dep[u]<(1<<i)) break;
anc[u][i].num=anc[anc[u][i-1].num][i-1].num;
anc[u][i].miny=min(anc[u][i-1].miny,anc[anc[u][i-1].num][i-1].miny);
}
for(int i=head[u];i;i=e[i].next)
{
int v=e[i].v;
if(vis[v]) continue;
anc[v][0].num=u;
anc[v][0].miny=e[i].w;
dep[v]=dep[u]+1;
dfs(v);
}
}
/*
void getfather() {
for(int i=1; i<=21; i++)
for(int j=1; j<=n; j++) {
anc[j][i].num=anc[anc[j][i-1].num][i-1].num;
anc[j][i].miny=min(anc[j][i-1].miny,anc[anc[j][i-1].num][i-1].miny);
}
}
*/
int lca(int x,int y) {
if(dep[x]<dep[y]) swap(x,y);
int s1=x,s2=y;
int tmp=dep[x]-dep[y];
for(int i=0;i<=21;i++)
if((1<<i)&tmp) s1=anc[s1][i].num;
/*
for(int i=22; i>=0; i--) {
if(dep[s1]+erk[i]<=dep[s2])
s1=anc[s1][i].num;
}
*/
if(s1==s2)
{
return min(getans(x,s1),getans(y,s1) );
}
for(int i=21; i>=1; i--)
{
if(anc[s1][i].num!=anc[s2][i].num)
s1=anc[s1][i].num;
s2=anc[s2][i].num;
}
// cout<<"lca:"<<s1<<endl;
// cout<<anc[x][0].num<<endl;
// cout<<anc[x][0].miny<<endl;
int temp1=getans(x,anc[s1][0].num);
int temp2=getans(y,anc[s2][0].num);
return min(temp1,temp2);
}
int main()
{
n=read();m=read();
for(int i=1; i<=n; i++)fa[i]=i;
for(int i=1; i<=m; i++)
{e1[i].s=read();e1[i].v=read();e1[i].w=read();}
sort(e1+1,e1+m+1,cmp);
int rest=n-1;
for(int i=1; i<=m; i++) {
int p1,p2;
p1=gf(e1[i].s);
p2=gf(e1[i].v);
if(p1==p2) continue;
fa[p1]=p2;
rest--;
add(p1,p2,e1[i].w);
add(p2,p1,e1[i].w);
if(!rest) break;
}
// for(int i=1; i<=21; i++) erk[i]=erk[i-1]<<1;
for(int i=1; i<=n; i++)
if(!vis[i]) dfs(i);
int q=read();
while(q--) {
int x=read();
int y=read();
if(gf(x)!=gf(y)) {
cout<<"-1"<<endl;
continue;
}
cout<<lca(x,y)<<endl;
}
return 0;
}
/*
5 7
4 3 4440
3 1 22348
1 3 28368
2 4 25086
5 3 6991
4 3 10638
3 1 11106
4
4 5
1 3
5 4
2 5
*/
```
0 条评论
信息
- ID
- 1843
- 难度
- 7
- 分类
- (无)
- 标签
- 递交数
- 5319
- 已通过
- 954
- 通过率
- 18%
- 被复制
- 10
- 上传者