题目链接:http://codeforces.com/problemset/problem/60/A

One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the left of the i-th box" ("To the left of i"), "Hidden to the right of the i-th box" ("To the right of i"). Such hints mean that there are no flakes in the i-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.
The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000) which represent the number of boxes and the number of hints correspondingly. Next m lines contain hints like "To the left of i" and "To the right of i", where i is integer (1 ≤ i ≤ n). The hints may coincide.
The answer should contain exactly one integer — the number of boxes that should necessarily be checked or "-1" if the hints are contradictory.
2 1 To the left of 2
1
3 2 To the right of 1 To the right of 2
1
3 1 To the left of 3
2
3 2 To the left of 2 To the right of 1
-1
题解:
方法一:贪心,由于区间范围只能是连续的,所以可以逐渐缩小范围。
方法二:差分法(还可适用于不连续的区间,比较通用的方法)。
区间并集:
1.当并集区间有一段时,可直接贪心,左右缩小范围。
2.当并集区间有多段时,使用差分法,然后再线段扫描(求前缀和)。
3.有关差分法的另一道题:http://blog.csdn.net/dolfamingo/article/details/72858734
贪心:
#include<bits/stdc++.h> using namespace std; typedef long long LL; const double eps = 1e-6; const int INF = 2e9; const LL LNF = 9e18; const int mod = 1e9+7; const int maxn = 1e3+10; int n,m, c[maxn]; int main() { cin>>n>>m; int B = 1; int l = 1, r = n; for(int i = 1; i<=m; i++) { int t; string s[5]; cin>>s[0]>>s[1]>>s[2]>>s[3]>>t; if(s[2]=="left") r = min(r,t-1); else l = max(l, t+1); } printf("%d ",(r-l+1>0)?(r-l+1):-1); }
差分法:
#include<bits/stdc++.h> using namespace std; typedef long long LL; const double eps = 1e-6; const int INF = 2e9; const LL LNF = 9e18; const int mod = 1e9+7; const int maxn = 1e3+10; int n, m, c[maxn]; int main() { cin>>n>>m; for(int i = 1; i<=m; i++) { int t; string s[5]; cin>>s[0]>>s[1]>>s[2]>>s[3]>>t; if(s[2]=="left") c[1]++, c[t]--; else c[t+1]++, c[n+1]--; } int cnt = 0; for(int i = 1; i<=n; i++) { c[i] += c[i-1]; if(c[i]==m) cnt++; } printf("%d ", cnt?cnt:-1); }