1018. Public Bike Management (30)

DFS求最短路径

#include<cstdio>
#include<cstring>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<cctype>
#include<vector>
#include<iomanip>
#include<queue>
#include<stack>
#include<cassert>
#define INF 0x3f3f3f3f
#define max(x,y) x > y ? x : y
#define min(x,y) x < y ? x : y 
using namespace std;
int bike[1007];
int map[1007][1007];
bool visited[1007];
int C, N, S, M, v, w, c, minCost = INF, minSend = INF, minBack = INF, cost, send, back;
vector<int> minRoad;
vector<int> curRoad;
void update(int curCost, int curSend, int curBack){
	minCost = curCost;
	minSend = curSend;
	minBack = curBack;
	minRoad = curRoad;
}
void dfs(int from, int to, int curCost, int curSend, int curBack){
	if(from == to){
		if(curCost == minCost){
			if(curSend == minSend){
				if(curBack < minBack) update(curCost, curSend, curBack);
			}
			else if(curSend < minSend) update(curCost, curSend, curBack);
		}
		else if(curCost < minCost) update(curCost, curSend, curBack);
	}
	else{
		for(int i = 1; i <= N; i ++){
			if(map[from][i] < INF && !visited[i]){
				visited[i] = 1;
				curRoad.push_back(i);
				cost = curCost + map[from][i];
				send = curSend;
				back = curBack;
				if(bike[i] + back < 0) send -= back + bike[i], back = 0;
				else back += bike[i];
				dfs(i, to, cost, send, back);
				visited[i] = 0;
				curRoad.pop_back();
			}
		}
	}
	
}
int main(){
	cin>>C>>N>>S>>M;
	memset(map, INF, sizeof(map));
	memset(visited, 0, sizeof(visited));
	for(int i = 1; i <= N; i ++){
		cin>>bike[i];
		bike[i] -= C / 2;
	}
	for(int i = 0; i < M; i ++){
		cin>>v>>w>>c;
		map[v][w] = c;
		map[w][v] = c;
	}
	curRoad.push_back(0);
	dfs(0, S, 0, 0, 0);
	cout<<minSend<<" ";
	bool f = 1;
	for(int i = 0; i < minRoad.size(); i++){
		if(!f) cout<<"->";
		else f = 0;
		cout<<minRoad[i];
	}
	cout<<" "<<minBack<<endl;
} 

阅读更多
个人分类: Algorithm PAT
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭