您的位置:首页 > 其它

poj-1724-ROADS(dfs)

2017-08-23 22:42 274 查看

题目地址

http://poj.org/problem?id=1724

题目大意

N个城市,编号1到N。城市间有R条单向道路。

每条道路连接两个城市,有长度和过路费两个属性。

Bob只有K块钱,他想从城市1走到城市N。问最短共需要走多长的路。如果到不了N,输

出-1

解题思路

深度优先搜索

剪枝

1) 如果当前已经找到的最优路径长度为L ,那么在继续搜索的过程中,总长度已经大

于L的走法,就可以直接放弃,不用走到底了

2) 用midL[k][m] 表示:走到城市k时总过路费为m的条件下,最优路径的长度。若在

后续的搜索中,再次走到k时,如果总路费恰好为m,且此时的路径长度已经超过

midL[k][m],则不必再走下去了。

Code

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <queue>
#include <map>
#include <vector>
#include <math.h>
#include <algorithm>
#define INF 0x3fffffff
#define N 110

using namespace std;
typedef long long LL;

int k, n, r;

struct Node {
int to;
int len;
int toll;
};

vector<Node> G
;

int mark
[11000];
bool vis
;
int g_min = INF;
int cur_cost = 0;
int cur_toll = 0;

void dfs(int x) {
if (x == n) {
if (cur_toll <= k) {
g_min = min(g_min, cur_cost);
return ;
} else {
return ;
}
}

for (int i = 0; i < G[x].size(); i++) {
int d = G[x][i].to;
if (!vis[d]) {
// cut
if (cur_toll + G[x][i].toll > k) continue;
if (cur_cost + G[x][i].len > g_min) continue;
if (cur_cost + G[x][i].len > mark[d][cur_toll+G[x][i].toll]) continue;
mark[d][cur_toll+G[x][i].toll] = cur_cost + G[x][i].len;

cur_cost += G[x][i].len;
cur_toll += G[x][i].toll;
vis[d] = 1;
dfs(d);

cur_cost -= G[x][i].len;
cur_toll -= G[x][i].toll;
vis[d] = 0;
}
}
}

int main() {

#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#else
//
#endif

while (cin >> k >> n >> r) {
int s;
Node node;
for (int i = 0; i < r; i++) {
cin >> s >> node.to >> node.len >> node.toll;
if (s != node.to) {
G[s].push_back(node);
}
}

for (int i = 0; i < N; i++) {
for (int j = 0; j < 10000; j++) {
mark[i][j] = INF;
}
}

memset(vis, 0, sizeof(vis));
g_min = INF;
cur_cost = 0;
cur_toll = 0;
vis[1] = 1;
dfs(1);
if (g_min == INF) {
cout << "-1" << endl;
} else {
cout << g_min << endl;
}
}
return 0;
}


参考

https://d396qusza40orc.cloudfront.net/pkupop/lectures/Week15/W15-02_%E6%B7%B1%E6%90%9C%E4%B9%8B%E5%AF%BB%E8%B7%AF%E9%97%AE%E9%A2%98.pdf
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: