题目描述
Bessie is running a taxi service for the other cows on the farm. The cows have been gathering at different locations along a fence of length M (1 <= M <= 1,000,000,000). Unfortunately, they have grown bored with their current locations and each wish to go somewhere else along the fence. Bessie must pick up each of her friends at their starting positions and drive them to their destinations. Bessie's car is small so she can only transport one cow in her car at a time. Cows can enter and exit the car instantaneously.
To save gas, Bessie would like to minimize the amount she has to drive. Given the starting and ending positions of each of the N cows (1 <= N <= 100,000), determine the least amount of driving Bessie has to do. Bessie realizes that to save the most gas she may need to occasionally drop a cow off at a position other than her destination.
Bessie starts at the leftmost point of the fence, position 0, and must finish her journey at the rightmost point on the fence, position M.
长度为m的栅栏上,有n头牛需要坐车前往别的地方,起点和终点分别为a_i和b_i。现在出租车从最左端0出发,要运送完所有牛,最后到达最右端m,求最小路程。
输入输出格式
输入格式:* Line 1: N and M separated by a space.
* Lines 2..1+N: The (i+1)th line contains two space separated
integers, s_i and t_i (0 <= s_i, t_i <= M), indicating the starting position and destination position of the ith cow.
输出格式:* Line 1: A single integer indicating the total amount of driving Bessie must do. Note that the result may not fit into a 32 bit integer.
输入输出样例
2 10
0 9
6 5
12
说明
There are two cows waiting to be transported along a fence of length 10. The first cow wants to go from position 0 (where Bessie starts) to position 9. The second cow wishes to go from position 6 to position 5.
Bessie picks up the first cow at position 0 and drives to position 6. There she drops off the first cow, delivers the second cow to her destination and returns to pick up the first cow. She drops off the first cow and then drives the remainder of the way to the right side of the fence.
Solution:
本题是一道很值得做的贪心。
首先,每一段的出发点到目标点的距离是一定要走的,所以$ans$可以先累加每一段的距离。
然后,我们不难想到尽可能的走有用的路(即尽可能的让牛在车上),但是由于最多载一个牛,所以一定有路程是不载牛的。
我们画画图,不难发现,每次回头的路程最少的情况,是从上一个点的终点到离他最近的起点的距离。
转换思路(类似于蚂蚁那道题的思路),每头牛都要从它所在起点走到一个终点然后消失同时该终点失效,相遇停下来等同于不停而是继续走到下一个最近的终点。
因为牛都是一样的,我们可以理解为当两头牛相遇在某一起点,另一头牛代替原牛走到最近的终点(然后就消失了,此终点失效),再回头载上个起点的牛往前走。发现每次回头的是当前最小的终点到当前最小的起点的距离,又由于从$0$出发要走到$m$,于是我们将$0$加入终点中,$m$加入起点中,从小到大排序,$ans$累加起点减去终点(取绝对值)。
贴张图理解一下:
代码:
#include<bits/stdc++.h> #define il inline #define ll long long #define For(i,a,b) for(int (i)=(a);(i)<=(b);(i)++) using namespace std; const int N=100005; int gi(){ int a=0;char x=getchar(); while(x<'0'||x>'9')x=getchar(); while(x>='0'&&x<='9')a=a*10+x-48,x=getchar(); return a; } int n,m,x[N],y[N]; ll ans; int main(){ n=gi(),m=gi(); For(i,1,n)x[i]=gi(),y[i]=gi(),ans+=abs(x[i]-y[i]); x[++n]=m,y[n]=0; sort(x+1,x+n+1),sort(y+1,y+n+1); For(i,1,n)ans+=abs(x[i]-y[i]); cout<<ans; return 0; }