POJ - 2431 - Expedition(贪心 + 优先队列)
题意:给定一条 L 长的路(1 <= L <= 10^6),途中有 n 个加油站(1 <= n <= 10^4),其中第 i 个加油站在距离终点Ai(1 <= Ai <= L)距离的地方,可以加Bi(1 <= Bi <= 100)单位油,设一单位距离耗一单位油,起点时有P(1 <= P <= 10^6)升油,求到达终点最少需要加多少次油,若无法到达终点则输出-1。
可以将此过程看作:每次尽可能走,直到消耗完目前所有的油,途中记录所有经过的加油站,然后在没油的时候取能加油量最大的加油站加油即可。
代码如下:
#include<cstdio> #include<cstring> #include<cctype> #include<cstdlib> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<deque> #include<queue> #include<stack> #include<list> #define fin freopen("in.txt", "r", stdin) #define fout freopen("out.txt", "w", stdout) #define pr(x) cout << #x << " : " << x << " " #define prln(x) cout << #x << " : " << x << endl #define Min(a, b) a < b ? a : b #define Max(a, b) a < b ? b : a typedef long long ll; typedef unsigned long long llu; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const ll LL_INF = 0x3f3f3f3f3f3f3f3f; const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f; const double pi = acos(-1.0); const double EPS = 1e-6; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const ll MOD = 1e9 + 7; using namespace std; #define NDEBUG #include<cassert> const int MAXN = 100 + 10; const int MAXT = 10000 + 10; struct Node{ int cur, fuel; bool operator < (const Node &rhs) const{ return fuel < rhs.fuel; } }p[MAXT]; bool cmp(const Node &a, const Node &b){ return a.cur < b.cur || (a.cur == b.cur && a.fuel > b.fuel); } int n, length, y; int main(){ while(scanf("%d", &n) == 1){ for(int i = 0; i < n; ++i) scanf("%d%d", &p[i].cur, &p[i].fuel); scanf("%d%d", &length, &y); for(int i = 0; i < n; ++i) p[i].cur = length - p[i].cur; p[n] = (Node){length, 0}; sort(p, p + n + 1, cmp); priority_queue<Node> q; bool flag = true; int lur = 0, fuels = y, ans = 0; for(int i = 0; i <= n; ++i){ if(p[i].cur - lur <= fuels){ fuels -= p[i].cur - lur; lur = p[i].cur; q.push(p[i]); } else{ while(!q.empty() && p[i].cur - lur > fuels){ const Node &u = q.top(); fuels += u.fuel; q.pop(); ++ans; } if(p[i].cur - lur <= fuels){ fuels -= p[i].cur - lur; lur = p[i].cur; q.push(p[i]); } else{ flag = false; break; } } } printf("%d\n", flag ? ans : -1); } return 0; }