莫名MLE
  • 板块灌水区
  • 楼主jiangjiang12
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/8/30 20:12
  • 上次更新2024/8/30 20:13:12
查看原帖
莫名MLE
1052371
jiangjiang12楼主2024/8/30 20:12

P1967求调!!!

#include <bits/stdc++.h>
using namespace std;
struct edge{
	int u, v, w;
}e[50005];
struct edge1{
	int to, nxt, limit;
}t[10005];
int head[10005], f[10005], ord[10005], depth[10005], parent[10005][15], st[10005][15], n, m, q, tot;
int find(int x){
	if(x==f[x]){return x;}
	f[x]=find(f[x]);
	return f[x];
}
void dfs(int p, int d){
	parent[p][0]=d;
	depth[p]=depth[d]+1;
	for(int i=head[p]; i; i=t[i].nxt){
		if(t[i].to==d){continue;}
		dfs(t[i].to, p);
		st[t[i].to][0]=t[i].limit;
	}
}
bool cmp(int x, int y){
	return e[x].w>e[y].w;
}
void kruskal(){
	for(int i=1; i<=n; i++){f[i]=i;}
	for(int i=1; i<=m; i++){ord[i]=i;}
	sort(ord+1, ord+m+1, cmp);
	for(int i=1; i<=m; i++){
		int x=find(e[ord[i]].u), y=find(e[ord[i]].v);
		if(x!=y){
			f[x]=y;
			t[++tot].to=y; t[tot].nxt=head[x]; head[x]=tot; t[tot].limit=e[ord[i]].w;
			t[++tot].to=x; t[tot].nxt=head[y]; head[y]=tot; t[tot].limit=e[ord[i]].w;
		}
	}
}
void pre(){
	for(int i=1; (1<<i)<n; i++){
		for(int j=1; j<=n; j++){
			parent[j][i]=parent[parent[j][i-1]][i-1];
			st[j][i]=min(st[j][i-1], st[parent[j][i-1]][i-1]);
		}
	}
}
int query(int x, int y){
	if(find(x)!=find(y)){return -1;}
	int res=1e9+7;
	if(depth[x]<depth[y]){swap(x, y);}
	int c=depth[x]-depth[y];
	for(int i=0; i<15; i++){
		if(c&(1<<i)){
			res=min(res, st[x][i]);
			x=parent[x][i];
		}
	}
	if(x==y){return res;}
	for(int i=14; i>=0; i--){
		if(parent[x][i]!=parent[y][i]){
			res=min(res, min(st[x][i], st[y][i]));
			x=parent[x][i]; y=parent[y][i];
		}
	}
	res=min(res, min(st[x][0], st[y][0]));
	return res;
}
int main(){
	scanf("%d%d", &n, &m);
	for(int i=1; i<=m; i++){
		scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].w);
	}
	kruskal();
	for(int i=1; i<=n; i++){
		if(f[i]==i){
			dfs(i, 0);
		}
	}
	pre();
	scanf("%d", &q);
	for(int a, b, i=1; i<=q; i++){
		scanf("%d%d", &a, &b);
		printf("%d\n", query(a, b));
	}
	return 0;
}
2024/8/30 20:12
加载中...