贪心算法为什么对这道题目不行
题目:
There are N problems numbered 1..N which you need to complete. You've arranged the problems in increasing difficulty order, and the ith problem has estimated difficulty level i. You have also assigned a rating vi to each problem. Problems with similar vi values are similar in nature. On each day, you will choose a subset of the problems and solve them. You've decided that each subsequent problem solved on the day should be tougher than the previous problem you solved on that day. Also, to not make it boring, consecutive problems you solve should differ in their vi rating by at least K. What is the least number of days in which you can solve all problems?
Input:
The first line contains the number of test cases T. T test cases follow. Each case contains an integer N and K on the first line, followed by integers v1,...,vn on the second line.
Output:
Output T lines, one for each test case, containing the minimum number of days in which all problems can be solved.
Constraints:
1 <= T <= 100
1 <= N <= 300
1 <= vi <= 1000
1 <= K <= 1000
------------------------------------------
Sample Input:
2
3 2
5 4 7
5 1
5 3 4 5 6
Sample Output:
2
1
Explanation:
For the first example, you can solve the problems with rating 5 and 7 on the first day and the problem with rating 4 on the next day. Note that the problems with rating 5 and 4 cannot be completed consecutively because the ratings should differ by at least K (which is 2). Also, the problems cannot be completed in order 5,7,4 in one day because the problems solved on a day should be in increasing difficulty level.
For the second example, all problems can be solved on the same day.
题目大意:
给出n个任务,每个任务的难度是任务的index,每个任务有rating。
一天中可以解决多个任务:但是每个任务之间有约束
第一:先解决简单的任务,后解决难的任务。也就是index需要递增
第二:一天中解决的问题中相邻两个任务之间ratting的difference 必须大于指定值K。
求需要的最小天数。
我的思路是这样的:
把任务放在一个有向图中,任务i, j
i<j and abs(rating[i]-rating[j]) >=K,就放一条有向边。
然后用贪心算法:
每次删除途中的最长边,和边上的结点,直到删除所有结点。
但是这样做的结果不对。
能给一下思路吗?谢谢。
[解决办法]
DAG的最小路径覆盖需要拆图然后用最大匹配做,这是有经典模型的。贪心肯定有反例的。一般的DAG很容易构造反例。要构造符合这道题的反例图可能不太容易,但既然你说WA了,那肯定是存在的。
安心去写最大匹配/最大流吧。