poj 3069 Saruman's Army 贪心 题解《挑战程序设计竞赛》

地址 http://poj.org/problem?id=3069

题解

题目可以考虑贪心 尽可能的根据题意选择靠右边的点

注意

开始无标记点 寻找左侧第一个没覆盖的点 再来推算既可能靠右的标记点为一轮

我最开始就是轮次的操作理解错误 结果wa了

ac代码如下

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 
 5 
 6 using namespace std;
 7 
 8 /*
 9 poj3069
10 
11 题目大意:一个直线上有N个点。点i的距离是Xi。
12 从这些点中选取若干个加上标记。
13 要求:对于每个点,与其距离为R的范围内必有做标记的点(包括自身)。
14 求至少标记多少点才能满足要求。
15 
16 输入
17 N=6 R =10
18 X={1 7 15 20 30 50}
19 输出 
20 3
21 
22 
23 Sample Input
24 
25 0 3
26 10 20 20
27 10 7
28 70 30 1 7 15 20 50
29 -1 -1
30 Sample Output
31 
32 2
33 4
34 */
35 int nodes[100010];
36 
37 int solve(int r,int n)
38 {
39     int count = 0;
40 
41     int leftNotCover = 0;
42     int currMark = 0;
43 
44     while (leftNotCover < n) {
45         //找到最左边 第一个未覆盖的点
46         if (leftNotCover != 0) {
47             while (currMark < n && nodes[leftNotCover] - nodes[currMark] <= r) leftNotCover++;
48             if (leftNotCover >= n) break;
49         }
50 
51         currMark = leftNotCover;
52         while (currMark < n && nodes[currMark] - nodes[leftNotCover] <= r) currMark++;
53         count++;
54         currMark = currMark - 1;
55         leftNotCover = currMark + 1;
56     }
57 
58 
59     return count;
60 }
61 
62 int main()
63 {
64     int r = 0;
65     int n = 0;
66     while (1) {
67         cin >> r >> n;
68         if (r == -1 || n == -1) return -1;
69 
70         for (int i = 0; i < n; ++i) {
71             cin >> nodes[i];
72         }
73         sort(nodes, nodes + n);
74         cout <<solve(r, n) << endl;
75     }
76 
77     return 0;
78 }
View Code
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/11995239.html