https://leetcode.com/problems/cheapest-flights-within-k-stops/description/
一开始写的不是n方的dp 然后感觉自己应该是错了。。。
剪枝+搜索:
struct Node {
string path;
int cnt;
int cost;
Node(string path, int cnt, int cost):path(path), cnt(cnt), cost(cost) {}
};
class Solution {
public:
int lastPos(string path) {
int pos = path.find_last_of(',');
return atoi( path.substr(pos+1).c_str() );
}
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
set<string> visit;
map< pair<int, int>, int > mat;
map< int, vector<int> > edges;
for (int i = 0; i < flights.size(); i++) {
mat[ make_pair(flights[i][0], flights[i][1]) ] = flights[i][2];
if (edges.find(flights[i][0]) == edges.end()) {
edges[flights[i][0]] = vector<int>{flights[i][1]};
} else {
edges[flights[i][0]].push_back( flights[i][1] );
}
}
queue<Node>q;
int ans = INT_MAX;
for (int j = 0; j < edges[src].size(); j++) {
int i = edges[src][j];
if (i == dst) {
// cout << "ans:" << ans << " flights[src][i]:" << mat[make_pair(src, i)] << endl;
ans = min(ans, mat[make_pair(src, i)]);
}
string path = to_string(src) + "," + to_string(i);
visit.insert(path);
q.push( Node(path, 0, mat[make_pair(src, i)]) );
}
while (!q.empty()) {
Node tp = q.front();
// cout << "tp:" << tp.cnt << " ->" << tp.cost << endl;
q.pop();
int last = lastPos(tp.path);
if (tp.cnt >= K || last == dst || tp.cost >= ans) continue;
for (int j = 0; j < edges[last].size(); j++) {
int i = edges[last][j];
string path = tp.path + "," + to_string(i);
if (visit.find(path) != visit.end()) continue;
visit.insert(path);
if (i == dst) {
// cout << "ans:" << ans << " flights[last][i]:" << tp.cost + mat[make_pair(last, i)] << endl;
ans = min(ans, tp.cost + mat[make_pair(last, i)]);
} else {
q.push(Node( path, tp.cnt + 1, tp.cost + mat[make_pair(last, i)] ));
}
}
}
return ans==INT_MAX?-1:ans;
}
};
然后看了这里的dp:https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/115548/C++-solution-using-Dynamic-Programming
class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
K++;
int dp[n][K+1];
for (int i = 0; i < n; i++) {
for (int k = 0; k <= K; k++) {
dp[i][k] = INT_MAX/2;
}
}
dp[src][0] = 0;
for (int i = 1; i <= K; i++) {
for (int j =0; j < n; j++) {
dp[j][i] = dp[j][i-1];
}
for (vector<int>&f : flights) {
dp[ f[1] ][i] = min( dp[ f[1] ][i], dp[f[0]][i-1] + f[2] );
}
}
return dp[dst][K] >= INT_MAX/2?-1:dp[dst][K];
}
};
实际可以进一步简化 https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/115596/c++-8-line-bellman-ford
class Solution {
public:
//bellman ford.
//just run it k+1 iterations.
int findCheapestPrice(int n, vector<vector<int>>& a, int src, int sink, int k) {
vector<int> c(n, 1e8);
c[src] = 0;
for(int z=0; z<=k; z++){
vector<int> C(c);
for(auto e: a)
C[e[1]] = min(C[e[1]], c[e[0]] + e[2]);
c = C;
}
return c[sink] == 1e8 ? -1 : c[sink];
}
};