1030 Travel Plan

1030 Travel Plan
优化《算法笔记》的算法,添加剪枝

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

const int maxn=501;
const int INF=100000000;
int N,M,S,D;
int G[maxn][maxn];
int cost[maxn][maxn];
int COST;
int tCOST;
int d[maxn];
bool vis[maxn]={false};
vector<int> Pre[maxn]; 
vector<int> path;
vector<int> tpath;

void Dijkstra(int s){
	fill(d,d+N,INF);
	d[s]=0;
	Pre[s].push_back(s);
	for(int i=0;i<N;i++){
		int u=-1,MIN=INF;
		for(int j=0;j<N;j++){
			if(!vis[j] && d[j]<MIN){
				u=j;
				MIN=d[j];
			}
		}
		if(u==-1) return ;
		vis[u]=true;
		for(int i=0;i<N;i++){
			if(!vis[i] && G[u][i]<INF){
				int t=d[u]+G[u][i];
				if(t<d[i]){
					d[i]=t;
					Pre[i].clear();
					Pre[i].push_back(u);
				} else if(t==d[i]){
					Pre[i].push_back(u);
				}
			}
		}
	}
}

void DFS(int v){
	if(v==S){
		COST=tCOST;
		path=tpath;
		return;
	}
	
	for(int i=0;i<Pre[v].size();i++){
		int u=Pre[v][i];
		if(tCOST+cost[u][v]<COST){
			tpath.push_back(u);
			tCOST+=cost[u][v];
			DFS(u); 
			tpath.pop_back();
			tCOST-=cost[u][v];
		}
	}
}

int main(void){
	scanf("%d%d%d%d",&N,&M,&S,&D);
	int c1,c2,dis,c;
	fill(G[0],G[0]+maxn*maxn,INF);
	for(int i=0;i<M;i++){
		scanf("%d%d%d%d",&c1,&c2,&dis,&c);
		G[c1][c2]=G[c2][c1]=dis;
		cost[c1][c2]=cost[c2][c1]=c;
	}
	Dijkstra(S);
	tpath.push_back(D);
	COST=INF;
	DFS(D);
	for(int i=path.size()-1;i>=0;i--){
		printf("%d ",path[i]);
	}
	printf("%d %d",d[D],COST);
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值