复赛准备 - 最短路径问题(dijkstra)

#include "iostream"
#include "vector"
#include "cmath"
#include "queue"
using namespace std;

const int N = 1e3;
const double INF = 1e10;

struct dist{
	int x;
	double l;
};

priority_queue<dist> qu;

bool operator < (const dist d1,const dist d2){
	return d1.l > d2.l;
}

struct edge{
	int to;//指向哪个点 
	double w;//权值:长度 
};


vector<edge> graph[N];

struct node{
	int x,y;
}nodes[N]; 

int n,m,s,t;//n个节点,m条边 

double dis[N];
int flag[N];


void addEdge(int from,int to);
void dijkstra(int x);

int main(){
	cin>>n;
	int x,y;
	for(int i=1;i<=n;i++){
		cin>>x>>y;
		nodes[i].x = x;
		nodes[i].y = y;
	}
	
	cin>>m;
	int from,to;
	for(int i = 1;i <= m;i++){
		cin>>from>>to;
		
		addEdge(from,to);
	}
	
//	//遍历看 
//	for(int i = 1; i <=n ;i++){
//		cout<<"节点"<<i<<":"<<endl;
//		for(int j = 0;j < graph[i].size();j ++){
//			cout<<"("<<graph[i][j].to<<" "<<graph[i][j].w<<") ";
//		} 
//		cout<<endl;
//	}
	
	cin>>s>>t;
	
	dijkstra(s);
	
	printf("%.2lf",dis[t]);
	
	
	return 0;
}

void addEdge(int from,int to){
	//从from到to的一条边;从to到from的边
	double l = sqrt((nodes[from].x - nodes[to].x) * (nodes[from].x - nodes[to].x)  + (nodes[from].y - nodes[to].y) * (nodes[from].y - nodes[to].y))  ; 
	
	graph[from].push_back({to,l});
	graph[to].push_back({from,l}); 
}


void dijkstra(int x){
	//初始化dis,flag
	for(int i=0;i<=n;i++){
		dis[i] = INF;
	}
	
	dis[x] = 0;
	qu.push({x,0});
	
	//O(n^2) - > O(nlogn)
	while(!qu.empty()){//O(n)
		
//		//打擂台找最小的点 
//		int p = 0;
//		for(int j = 1; j <= n;j ++){//O(n) - >logn
//			if(!flag[j] && dis[j] < dis[p]){
//				p = j;
//			} 
//		}

		dist mn = qu.top();qu.pop();
		
		if(flag[mn.x]){
			continue;
		}
		
		int p = mn.x;
		
		

		
		//优化操作
//		if(dis[p] == 10000){
//			break;
//		} 
		
		flag[p] = 1;
		
		//松弛操作
		for(int j = 0;j < graph[p].size(); j ++){
			int to = graph[p][j].to;
			double w = graph[p][j].w;
			
			if(dis[p] + w < dis[to]){
				dis[to] = dis[p] + w;
				qu.push({to,dis[to]});//优化版本 
			}
			
		} 
		
		
	}
	
		 
}

上一篇:Java-Tomcat服务器


下一篇:LeetCode_除法求值