您的位置:首页 > 编程语言 > C语言/C++

1018. Public Bike Management (30)

2016-02-20 11:37 609 查看
   DFS找符合条件的路径

#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <limits>

using namespace std;

int cmax, n, sp, m, half;

vector<bool> used;
vector<int> bikes;
vector<vector<int>> edges;

int minTime = numeric_limits<int>::max();
int minSend = numeric_limits<int>::max();
int minCollect = numeric_limits<int>::max();
vector<int> minPath;

void dfs(int s, int curTime, int curSend, int curCollect, vector<int>& curPath){
if(s == sp){
bool choosed = curTime < minTime
|| (curTime == minTime && curSend < minSend)
|| (curTime == minTime && curSend == minSend && curCollect < minCollect);

if(choosed){
minTime = curTime;
minSend = curSend;
minCollect = curCollect;
minPath = curPath;
}

return;
}

if(curTime > minTime) return;

for(int i = 1; i <= n; ++i){
if(!used[i] && edges[s][i] != -1){
used[i] = true;
curPath.push_back(i);

if(curCollect + bikes[i] < half){
dfs(i, curTime + edges[s][i], curSend + half - bikes[i] - curCollect, 0, curPath);
}else{
dfs(i, curTime + edges[s][i], curSend, bikes[i] + curCollect - half, curPath);
}

used[i] = false;
curPath.pop_back();
}
}
}

int main(){
scanf("%d%d%d%d", &cmax, &n, &sp, &m);
half = cmax / 2;

used.resize(n+1, false);
bikes.resize(n+1);
edges.resize(n+1);
for(auto& edge : edges){
edge.resize(n+1, -1);
}

for(int i = 1; i <= n; ++i){
scanf("%d", &bikes[i]);
}

for(int i = 0; i < m; ++i){
int si, sj, tij;
scanf("%d%d%d", &si, &sj, &tij);
edges[si][sj] = edges[sj][si] = tij;
}

vector<int> curPath;
dfs(0, 0, 0, 0, curPath);

printf("%d 0", minSend);
for(auto& n : minPath){
printf("->%d", n);
}

printf(" %d", minCollect);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息