CSP-J复赛冲刺必刷题 | P3076 Taxi G

学习C++从娃娃抓起!记录下CSP-J备考学习过程中的题目,记录每一个瞬间。

附上汇总贴:CSP-J复赛冲刺必刷题 | 汇总_热爱编程的通信人的博客-CSDN博客


【题目描述】

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头牛需要坐车前往别的地方,起点和终点分别为ai和bi。现在一辆出租车从最左端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, si and ti (0 <= si, ti <= 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

【代码详解】

#include <bits/stdc++.h>
using namespace std;
int st[1000005], ed[100005];
long long ans = 0;
int main()
{
    int n, m;
    cin >> n >> m;
    for (int i=1; i<=n; i++) {
        cin >> st[i] >> ed[i];
        ans += abs(st[i]-ed[i]);  //累加每段至少要走的距离
    }
    st[n+1] = m;
    ed[n+1] = 0;
    sort(st+1, st+n+2);
    sort(ed+1, ed+n+2);
    for (int i=1; i<=n+1; i++) {
        ans += abs(ed[i]-st[i]);  //还要加上空车行驶的距离
    }
    cout << ans;
    return 0;
}

【运行结果】

2 10 
0 9 
6 5 
12

猜你喜欢

转载自blog.csdn.net/guolianggsta/article/details/133495663