Day 47 算法笔记之提高篇(4)10.4 最短路径

目录

1.Dijkstra算法

1.1邻接矩阵

1.2邻接表

1.3路径

1.4新增边权

1.5新增点权

1.6最短路径数

1.7Emergency

1.8配合DFS

1.8.1找出路径

1.8.2DFS遍历

1.8.3  Travel Plan


1.Dijkstra算法

1.1邻接矩阵

const int maxv=1000;
const int inf = 100000000;

int n,g[maxv][maxv];
int d[maxv];
bool vis[maxv] = {false};

void dijkstra(int s){
	fill(d,d+maxv,inf);
	d[s] = 0;
	for(int i=0;i

1.2邻接表

const int maxv=1000;
const int inf = 100000000;

struct node{//目标顶点,边权 
	int v,dis;
};
vector adj[maxv];
int n;
int d[maxv];
bool vis[maxv] = {false};

void dijkstra(int s){
	fill(d,d+maxv,inf);
	d[s] = 0;
	for(int i=0;i

1.3路径

void dfs(int s,int v){
	if(v==s){
		printf("%d\n",s);
		return;
	}
	dfs(s,pre[v]);
	printf("%d\n",v);
}

1.4新增边权

for(int v=0;v

1.5新增点权

for(int v=0;vw[v]){
			w[v] = w[u] + weight[v];
		}
	}
}

1.6最短路径数

for(int v=0;v

1.7Emergency

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;

const int maxv = 510;
const int inf = 1000000000;

int n,m,st,ed,g[maxv][maxv],weight[maxv];
int d[maxv],w[maxv],num[maxv];
bool vis[maxv] = {false};

void dijkstra(int s){
	fill(d,d+maxv,inf);
	memset(w,0,sizeof(w));
	d[s] = 0;
	w[s] = weight[s];
	num[s] = 1;
	for(int i=0;iw[v]){
						w[v] = w[u] + weight[v];
					}
					num[v] += num[u];
				}
			}
		}
	}
}

int main(){
	
	scanf("%d%d%d%d",&n,&m,&st,&ed);
	for(int i=0;i

1.8配合DFS

1.8.1找出路径

const int maxv = 510;
const int inf = 1000000000;

vector pre[maxv];
void dijkstra(int s){
	fill(d,d+maxv,inf);
	d[s] = 0;
	for(int i=0;i

1.8.2DFS遍历

int optvalue;
vector pre[maxv];
vector path,temppath;
void dfs(int v){
	
	if(v==st){
		temppath.push_back(v);
		int value;
		计算value;
		if(value优于optvalue){
			optvalue = value;
			path = temppath;
		}
		temppath.pop_back();
		return;
	}
	
	temppath.push_back(v);
	for(int i=0;i

1.8.3  Travel Plan

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;

const int maxv = 510;
const int inf = 1000000000;

int n,m,st,ed,g[maxv][maxv],cost[maxv][maxv];
int d[maxv],c[maxv],pre[maxv];
bool vis[maxv]={false};

void dijkstra(int s){
	fill(d,d+maxv,inf);
	fill(c,c+maxv,inf);
	for(int i=0;i
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;

const int maxv = 510;
const int inf = 1000000000;

int n,m,st,ed,g[maxv][maxv],cost[maxv][maxv];
int mincost=inf;
int d[maxv];
bool vis[maxv]={false};

vector pre[maxv];
vector temppath,path;

void dijkstra(int s){
	fill(d,d+maxv,inf);
	d[s] = 0;
	
	for(int i=0;i0;i--){
			int id=temppath[i],idnext=temppath[i-1];
			tempcost += cost[id][idnext];
		}
		if(tempcost=0;i--){
		printf("%d ",path[i]);
	}
	printf("%d %d\n",d[ed],mincost);
	
	return 0;
}

你可能感兴趣的:(算法,c语言,开发语言)