1st Junior Balkan Olympiad in Informatics Boats 船 DP

Boats

Magicians have to come to the great assembly of Aglargond School of Magic. They can
come with boats, among other ways. Organizers have reserved a ring for every participant,
so he can tie his boat to the ring assigned uniquely to him. Every magician has sent the
length of his boat to the organizers. The boat has to be tied so that the ring is somewhere
on the length of the boat including endpoints of the boat. End of the boats can touch each
other, but boats cannot overlap (see the picture). Because of this restriction it is possible
that all boats cannot be tied at the same time. Organizing committee of the Magician
Assembly asked you to write the program BOATS that finds the maximal number of the
boats which can be tied at the same time to the assigned rings.

Input
The first line of input contains number of magicians, N (1 ≤ N ≤ 10000). In each of the
following N lines there are exactly two space separated integers li and pi (1 ≤ li, pi ≤ 100000,
1 ≤ i ≤ N) representing the length of the boat and the position of the assigned ring along
the river bank starting from the school building. No two rings have the same position.


Output
The output has exactly one line containing one number – maximal number of boats.


Example
Input

7
5 9
2 17
6 10
3 11
2 16
4 13
5 6

Output

5 

分析

 我们从简单的想起。首先,第一艘船一定是右端和木桩相连。贪心的想法,我们把所有的船都尽量向左靠。

接下来,我们来想,如何判断一条船放,还是不放。影响这条船“能否放”的条件是前一艘船的最右端到达了什么位置。有这几种情况:

  1. 前面一艘船不会占据这条船靠岸的位置
  2. 前面一艘船占据了木桩位置
    1. 前一艘船不放,放当前船(船总数不变),会有更优的右端点
    2. 前一艘船不放,没有更优端点,因此这条船不放

第一种大情况:显然放啊

第二种大情况:若有更优解,前一艘不放,当前放;若没有,不改变,看下一艘船

程序

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int MAXN = 10000 + 1;
 4 int n, Ans = 1, R, Last_R;
 5 struct node
 6 {
 7     int l, loc;
 8 }ship[MAXN];
 9 bool comp(node x, node y)
10 {
11     return x.loc < y.loc;
12 }
13 int main()
14 {
15     freopen("boats.in","r",stdin); 
16     freopen("boats.out","w",stdout);
17     cin >> n;
18     for (int i = 1; i <= n; i++)
19         cin >> ship[i].l >> ship[i].loc;
20     sort(ship+1, ship+(n+1),comp);
21     R = ship[1].loc; 
22     for (int i = 2; i <= n; i++)
23     {
24         if (ship[i].loc >= R)
25         {
26             Last_R = R;
27             R = max(R+ship[i].l,ship[i].loc);
28             Ans++;
29         }
30         else
31         {
32             int temp=max(Last_R+ship[i].l,ship[i].loc);
33             R = min(temp,R);
34         }
35     }
36     cout << Ans << endl;
37     return 0;
38 }
原文地址:https://www.cnblogs.com/OIerPrime/p/8545667.html