This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
/** | |
* @param target: The target distance | |
* @param original: The original gas | |
* @param distance: The distance array | |
* @param apply: The apply array | |
* @return: Return the minimum times | |
*/ | |
int getTimes(int target, int original, vector<int> &distance, vector<int> &apply) { | |
int len = distance.size(), layer = 0; | |
queue<pair<int, int>> q; | |
q.emplace(-1, original); | |
while (q.size()) | |
{ | |
int sz = q.size(); | |
for (int i = 0; i < sz; ++i) | |
{ | |
auto node = q.front(); | |
q.pop(); | |
vector<pair<int, int>> adjs; | |
//get all adjacent nodes(reachable nodes) | |
int idx = node.first, remain = node.second, dist = idx < 0? 0: distance[idx], len = distance.size(); | |
if(idx >= 0)remain += apply[idx]; | |
if (dist + remain >= target)return layer; | |
for (int i = idx + 1; i < len; ++i) | |
{ | |
if (distance[i] > dist + remain)break; | |
adjs.emplace_back(i, remain - (distance[i] - dist)); | |
} | |
for (const auto& adj : adjs)q.push(adj); | |
} | |
++layer; | |
} | |
return -1; | |
} | |
}; |
No comments:
Post a Comment