题解:P2209 [USACO13OPEN] Fuel Economy S
lichengxi1111 · · 题解
前言
- 题面比较坑,没有说
n 的范围,事实上n \le 5 \times 10^4 - 不开
long long见祖宗
题意回顾
给定四个正整数
意为初始时有
货车从坐标零点处出发,每走1单位距离就会消耗1升油,在每个供油站均可补充任意升油(需要保证供油后油桶不超过限制),花费数量乘单价元钱,求走到终点(坐标为
Solution
Part1
首先需要判定无解的情况,容易考虑到3种情况:
-
- 存在
i \in [1,n) ,使得g < x_{i + 1} - x_{i} - 无法从第
n 个供油站走到d ,即g < d - x_{n}
核心代码如下:
a[n + 1].x = d,a[n + 1].y = 0;
if(a[1].x > b){
cout << "-1" << endl;
return 0;
}
for(int i = 2;i <= n + 1;++i){
if((a[i].x - a[i - 1].x) > g){
cout << "-1" << endl;
return 0;
}
}
Part2
接下来我们考虑有解的情况,可以考虑贪心
首先对于起点来说,肯定是在消耗油量不超过
其次,对于任何一个供油站
- 在消耗不超过
g 的情况下,能够找到比当前供油站单价小的供油站,那我们肯定跳到第一单价更小的供油站,则花费为(x_{now} - x_{pos} - rest) \times y_{pos} ,其中now 为第一个花费小于当前所在供油站的供油站编号 - 在消耗不超过
g 的情况下,找不到比当前供油站花费小的供油站,则我们需要在当前供油站买的越多越好,则买满整个邮箱,花费为(g - rest) \times y_{pos}
\mathscr{AC \ Code}
综上,我们可以得出代码:
#include<iostream>
#include<algorithm>
using namespace std;
#define int long long
const int MAXN = 5e4 + 10;
struct Node{
int x,y;
bool operator<(const Node &a)const{
return x < a.x;
}
}a[MAXN];
int n,g,b,d,ans;
int find(int pos,int l){
int minn = n + 2,now = pos + 1;
while(a[now].x - a[pos].x <= l && now <= n + 1){
if(a[now].y < a[pos].y) return now;
if(a[now].y < a[minn].y) minn = now;
++now;
}
return minn;
}
signed main(){
ios::sync_with_stdio(false);
cin >> n >> g >> b >> d;
for(int i = 1;i <= n;++i) cin >> a[i].x >> a[i].y;
sort(a + 1,a + n + 1);
a[n + 1].x = d,a[n + 1].y = 0;
a[n + 2].y = 1e9;
if(a[1].x > b){
cout << "-1" << endl;
return 0;
}
for(int i = 2;i <= n + 1;++i){
if((a[i].x - a[i - 1].x) > g){
cout << "-1" << endl;
return 0;
}
}
int pos = find(0,b),rest = b - a[pos].x;
while(pos <= n){
int now = find(pos,g);
if(a[now].y < a[pos].y){
ans += (a[now].x - a[pos].x - rest) * a[pos].y;
rest = 0;
}
else{
ans += (g - rest) * a[pos].y;
rest = (g - (a[now].x - a[pos].x));
}
pos = now;
}
cout << ans << endl;
return 0;
}