pat 1030 Travel Plan

虽然是30分题,其实是简单题,只怪自己不清晰,想到什么dijskra和bellmanford的去了,浪费了不少时间。后来直接用DFS解决。

//1030 23:00
#include<stdio.h>
const int NUM=505;
const int INF=0x7fffffff;


int map[NUM][NUM],cost[NUM][NUM];
int visit[NUM];
int path[NUM][NUM],ans[NUM];
int n,src,d;

int mincost=INF,minpath=INF,indexi=0,indexj=1;

int totalCost=0,totalpath=0,minj;

void init()
{
	int i,j;
	for(i=0;i<n;i++){
		for(j=0;j<n;j++){
			cost[i][j]=map[i][j]=INF;
			cost[j][i]=map[j][i]=INF;
			
		}
		cost[i][i]=map[i][i]=0;
		
	}
}
void dfs(int id)
{
	int i;
	visit[id]=1;

	if(id==d){//到达终点,将路径,花费都记录到path[][]中
		
		if(minpath>=totalpath&&mincost>totalCost){//开始忘了加minpath
			minpath=totalpath;
			mincost=totalCost;
			for(i=0;i<indexj;i++){
				path[indexi][i]=ans[i];
			}
			minj=indexj;//这条可行路径的顶点数
			indexi++;//方案数+1
		}
		


		
		return ;
	}

	for(i=0;i<n;i++){
		if(visit[i]==0&&map[id][i]!=INF){
			totalpath+=map[id][i];//当前总路程
			totalCost+=cost[id][i];//当前总花费
			ans[indexj++]=i;//记录路径
			dfs(i);
			visit[i]=0;//回溯
			totalCost-=cost[id][i];
			totalpath-=map[id][i];
			indexj--;

		}
	}
}
int main()
{
	int m,i,j;
	int c1,c2,l,c;
	//freopen("C:\\Documents and Settings\\Administrator\\桌面\\input.txt","r",stdin);

	scanf("%d%d%d%d",&n,&m,&src,&d);
	if(src==d){
		printf("%d 0 0",src);
		return 0;
	}
	init();
	for(i=0;i<n;i++)
			visit[i]=0;
	for(i=0;i<m;i++){
		scanf("%d%d%d%d",&c1,&c2,&l,&c);
		map[c2][c1]=map[c1][c2]=l;
		cost[c2][c1]=cost[c1][c2]=c;
	}
	ans[0]=src;
	dfs(src);
	if(indexi==0)
		printf("No\n");
	else {

			indexi--;
			printf("%d",path[indexi][0]);
			for(j=1;j<minj;j++){
				printf(" %d",path[indexi][j]);
			}
			printf(" %d %d",minpath,mincost);


	}
	return 0;

}


 

你可能感兴趣的:(pat 1030 Travel Plan)