返回题解分享
讨论 / 题解分享/ 帖子详情

奶牛跨栏 - 题解

//奶牛跨栏
//https://dashoj.com/p/141
//dijkstra+图+邻接表+求瓶颈最短路的最小值
#include <bits/stdc++.h>

using namespace std;
using pi = pair<int,int>;

const int N = 301;
const int INF = 0x3f3f3f3f;

struct node{
	int v;
	int dis;
	bool operator < (const node & a) const{
		return dis > a.dis;
	}
};

vector<pi> adj[N];
int dist[N][N];//起点到终点的最短路 ,也充当记忆数组
bool flag[N];//是否在S中 

void dijkstra(int u){
	priority_queue<node> pq;
	for(int i = 0;i < N;i++){
		dist[u][i] = INF; 
	} 
	dist[u][u] = 0;
	pq.push({u,0});	
	memset(flag, 0, sizeof(flag));//必要,不然会出bug 
	while(!pq.empty()){
		node it = pq.top();
		pq.pop();
		int t = it.v;
		if(flag[t]){
			continue;
		}
		flag[t] = true;
		for(auto edge : adj[t]){
			int i = edge.first;
			int w = edge.second;
			if(!flag[i] && dist[u][i] > max(dist[u][t],w)){
				dist[u][i] = max(dist[u][t],w);
				pq.push({i,dist[u][i]});
			} 
		}
	}
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    
	int n,m,t;
	int s,e,h;
	cin >> n >> m >> t;
	while(m--){
		cin >> s >> e >> h;
		adj[s].push_back({e,h});
	}
	
	for (int i = 0; i < N; i++) {
    	for (int j = 0; j < N; j++) {
        	dist[i][j] = INF;
    	}
	}
	
	while(t--){
		int st,et;
		cin >> st >> et;
		int& res = dist[st][et];
		if(res != INF){
			cout << res << "\n";
			continue;
		}
		dijkstra(st);
		
		if(res == INF){
			cout << -1 << "\n";
		}else{
			cout << res << "\n";
		}
	}
	return 0;
}
0 回复 0 转发 0 喜欢 2 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!