[USACO13OPEN]照片Photo
题目描述
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(1 <= N <= 200,000)头奶牛制作一张全家福照片,N头奶牛编号1到N。
于是约翰拍摄了M(1 <= M <= 100,000)张照片,每张照片都覆盖了连续一段奶牛:第i张照片中包含了编号a_i 到 b_i的奶牛。但是这些照片不一定把每一只奶牛都拍了进去。
在拍完照片后,约翰发现了一个有趣的事情:每张照片中都有一只身上带有斑点的奶牛。约翰意识到他的牛群中有一些斑点奶牛,但他从来没有统计过它们的数量。 根据照片,请你帮约翰估算在他的牛群中最多可能有多少只斑点奶牛。如果无解,输出“-1”。
Input
输入输出格式
输入格式:
-
Line 1: Two integers N and M.
- Lines 2..M+1: Line i+1 contains a_i and b_i.
输出格式:
- Line 1: The maximum possible number of spotted cows on FJ's farm, or -1 if there is no possible solution.
输入输出样例
5 3 1 4 2 5 3 4
1
题解:
这道题,要画画图理解才行。其实就是要求
1.在每个区间里面都必须要有一棵树被砍。
2.并且每个区间里面都必须只有一棵树被砍。
这两句话很关键。于是我们可以根据这两个条件做dp。
首先我们设f[i]为前i个树满足条件且最多能有多少树没有被砍,便有f[i]=max(f[j])+1
那么j的范围呢?
根据条件1,我们可以确定左边界
(因为必须选,那么上一个区间也一定要选,故j一定是>=最靠近i左边的区间的左坐标)
根据条件2,我们可以确定右边界。
(因为必须选一个,所以包含i的区间里面的任意一个j都不能转移,即j<=包含i的区间的最小的左坐标)
故我们可以根据这些限定用单调队列来优化原来的dp方程。
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 using namespace std; 6 struct Messi 7 { 8 int l,r; 9 }a[200103]; 10 int n,m,rp[200103],lp[200101],q[500101],f[200101]; 11 int main() 12 {int i,j,head,tail; 13 //freopen("search.in","r",stdin); 14 //freopen("search.out","w",stdout); 15 cin>>n>>m; 16 for (i=1;i<=n+1;i++) 17 rp[i]=i-1; 18 for (i=1;i<=m;i++) 19 { 20 scanf("%d%d",&a[i].l,&a[i].r); 21 lp[a[i].r+1]=max(lp[a[i].r+1],a[i].l); 22 rp[a[i].r]=min(rp[a[i].r],a[i].l-1); 23 } 24 for (i=n;i>=1;i--) rp[i]=min(rp[i],rp[i+1]); 25 for (i=2;i<=n+1;i++) lp[i]=max(lp[i],lp[i-1]); 26 j=1; 27 head=tail=1; 28 for (i=1;i<=n+1;i++) 29 { 30 while (j<=rp[i]&&j<=n) 31 { 32 if (f[j]==-1) 33 { 34 j++; 35 continue; 36 } 37 while (f[j]>f[q[tail]]&&tail>=head) tail--; 38 ++tail; 39 q[tail]=j; 40 j++; 41 } 42 while (q[head]<lp[i]&&head<=tail) head++; 43 if (head<=tail) f[i]=f[q[head]]+(i!=n+1?1:0); 44 else f[i]=-1; 45 } 46 if (f[n+1]!=-1) 47 cout<<f[n+1]; 48 else cout<<-1; 49 }