bzoj 3126 [Usaco2013 Open]Photo DP+单调队列

Description
Farmer John has decided to assemble a panoramic photo of a lineup of his N cows (1 <= N <= 200,000), which, as always, are conveniently numbered from 1…N. Accordingly, he snapped M (1 <= M <= 100,000) photos, each covering a contiguous range of cows: photo i contains cows a_i through b_i inclusive. The photos collectively may not necessarily cover every single cow. After taking his photos, FJ notices a very interesting phenomenon: each photo he took contains exactly one cow with spots! FJ was aware that he had some number of spotted cows in his herd, but he had never actually counted them. Based on his photos, please determine the maximum possible number of spotted cows that could exist in his herd. Output -1 if there is no possible assignment of spots to cows consistent with FJ’s photographic results.

给你一个n长度的数轴和m个区间,每个区间里有且仅有一个点,问能有多少个点

Input

  • Line 1: Two integers N and M.

  • Lines 2…M+1: Line i+1 contains a_i and b_i.

Output

  • Line 1: The maximum possible number of spotted cows on FJ’s farm, or -1 if there is no possible solution.

Sample Input
5 3

1 4

2 5

3 4

INPUT DETAILS: There are 5 cows and 3 photos. The first photo contains cows 1 through 4, etc.
Sample Output
1

OUTPUT DETAILS: From the last photo, we know that either cow 3 or cow 4 must be spotted. By choosing either of these, we satisfy the first two photos as well.
HINT

传送门
(似乎是权限题,不过洛谷上有同名题)
一开始以为是贪心,但是后面发现是dp。
题目要求是点覆盖所有区间,以及无多点在同一区间。
可以考虑一下选取了某一个点后,选其它点有什么要求。
假设选取数轴上一点i,然后1–i数轴上所有数轴都已经选完了的话,有没有可转移呢?
选取某一点i后,包含它的所有区间的左端点的最小值为L的话,
那么要满足无多点在同一区间,在i前面选取的点j必须在L的左边。
满足这条后,还有一条,就是点要覆盖所有区间。
也就是说j和i之间不能有“空出来的区间”。
换句话说,不能有一个区间[L,R],使j

概括一下,j的左范围是R j的右范围是R>i的区间中,L最小的那个-1(实际上应该是同时满足L<=i的区间,但是如果最小的L仍然大于i,是可以在后面舍去的)设为MIN[i]
然后可以进行转移(对于i后面那部分,到后面可以枚举到)

f[i]=max{f[j]+1} MAX[i]<=j<=MIN[i]

随着i的推移很显然MAX和MIN具有同样的不减单调性,因此可以用单调队列优化至O(N)。

关于代码部分还有点小问题,比如如何处理MAX和MIN。
事实上这个只要正反扫一遍就好了。
DP的时候我一直打不对,后面是借鉴了网上的代码的。
就是在数轴末端增加一个点(n+1),这样子可以处理掉很多范围统计答案的问题。
另外f[0]=0是需要用到的,初始化要注意。
一开始单调队列是先更新头再更新尾,但事实上会出现j无区间可取的情况,
因此需要先尾再头
有些i点无法取,直接令f[i]=-1,最后的答案都会归到n+1去(MIN[n+1]=n,MAX[n+1]=1)。

#include
using namespace std;
int read(){
	int f=1,x=0;char ch=getchar();
	while (ch<'0' || ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0' && ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return f*x;
}
int n,m,f[200005],Q[200005];
int MIN[200005],MAX[200005];
struct Range{int l,r;}a[100005];
bool cmp(Range x,Range y){return x.r=i) MIN[i]=min(MIN[i],a[pos].l-1),pos--;
	}
}
void dealMAX(){
	int pos=1;MAX[0]=0;MAX[n+1]=1;
	for (int i=1;i<=n;i++){
		MAX[i]=MAX[i-1];
		while (pos<=m && a[pos].rf[Q[tail]]) tail--;
			Q[++tail]=j++;
		}
		while (head<=tail && Q[head]

你可能感兴趣的:(DP/记忆化搜索,队列)