我们把延迟当作边的权值
#include<iostream> #include<algorithm> #include<cstring> #include<vector> #include<queue> using namespace std ; const int N = 2e5 +10 ; struct edge{ int from , to ; edge(int fromm , int too ){ from = fromm , to = too ; } }; vector<edge> e[N] ; struct s_node{ int id; long long n_dis ; s_node(int idd, long long n_diss){ id = idd , n_dis = n_diss ; } bool operator < (const s_node &o) const { return n_dis > o.n_dis ; } }; int n , m ; long long dis[N] ; int t[N] ; bool done[N] ; void dijkstra(int s, int final){ memset(dis,0x3f,sizeof(dis)) ; memset(done, 0 , sizeof(done)) ; dis[s] = 0 ; priority_queue<s_node> q ; q.push(s_node(s,dis[s])) ; while(!q.empty()){ s_node u = q.top() ; q.pop() ; if(u.id == final) return ; if(done[u.id]) continue ; done[u.id] = 1 ; for(int i = 0 ; i < e[u.id].size() ; i ++){ edge y = e[u.id][i] ; if(done[y.to]) continue ; if(dis[y.to] > dis[u.id] + t[u.id]){ dis[y.to] = dis[u.id] + t[u.id] ; q.push(s_node(y.to , dis[y.to])) ; } } } } int main(){ cin >> n >> m ; for(int i = 1 ; i < n ;i ++){ int a , b ; cin >> a >> b ; e[a].push_back({a,b}) ; e[b].push_back({b,a}) ; t[a] ++ , t[b] ++ ; } while(m --){ int l , r ; cin >> l >> r ; dijkstra(l,r) ; cout << dis[r] + t[r] << endl ; } return 0 ; }