1. 程式人生 > 實用技巧 >dijikstra 堆優化

dijikstra 堆優化

#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;
const int INF=1<<30;
int n,m;
int head[maxn],dis[maxn],cnt;
bool vis[maxn];

struct qwq{
	int from,to,next;
	int len;
}edge[maxn*2];

struct Node{
	int id,dist;
	bool operator < (const Node &x)const{
		return dist>x.dist;
	}
};

priority_queue<Node> q;

void add(int u,int v,int w){
	cnt++;
	edge[cnt].from=u;
	edge[cnt].to=v;
	edge[cnt].len=w;
	edge[cnt].next=head[u];
	head[u]=cnt;
	return;
}

void Dijikstra(int s){
	for(int i=1;i<=n;i++)dis[i]=INF,vis[i]=0;
	dis[s]=0;
	q.push(Node{s,0});
	while(!q.empty()){
		Node x=q.top(); q.pop();
		int u=x.id;
		if(vis[u])continue;
		vis[u]=1;
		for(int i=head[u];i;i=edge[i].next){
			if(dis[edge[i].to]>dis[edge[i].from]+edge[i].len){
				dis[edge[i].to]=dis[edge[i].from]+edge[i].len;
				q.push(Node{edge[i].to,dis[edge[i].to]});
			}
		}
	}
}

int main(){
	scanf("%d",&n);
	for(int i=1;i<n;i++){
		static int u,v;
		scanf("%d%d",&u,&v);
		add(u,v,1);
		add(v,u,1);
	}
	int Q;
	scanf("%d",&Q);
	for(int i=1;i<=Q;i++){
		static int s,t;
		scanf("%d%d",&s,&t);
		Dijikstra(s);
		printf("%d\n",dis[t]);
	}
	return 0;
}