直接上正题。
观察到 (我把题中的 , 改为 ,)。
然后就可以差分了。
首先先要确定你会差分。
每次操作 在 的位置上加上 ,在 的位置上减去 ,维护每个位置的这个值为 。
然后对于第 个位置,种树的个数即为 。
这是差分板子,很好理解,看不懂可以自己搜。
答案即为 ,这个可以前缀和。
时间复杂度为 ,其中 是值域,题目中为 。
# include <bits/stdc++.h>
# define int long long
# define up(i ,x ,y) for (int i = x ; i <= y ; i ++)
# define dn(i ,x ,y) for (int i = x ; i >= y ; i --)
# define inf 1e14
using namespace std;
inline int read (){int s = 0 ; bool w = 0 ; char c = getchar () ; while (!isdigit (c)) {w |= (c == '-') ,c = getchar () ;} while (isdigit (c)){s = (s << 1) + (s << 3) + (c ^ 48) ; c = getchar ();}return w ? -s : s;}
inline void write (int x){if (x < 0) putchar ('-') ,x = -x; if (x > 9) write (x / 10) ; putchar (x % 10 | 48);}
inline void writesp (int x){write (x) ,putchar (' ');}
inline void writeln (int x){write (x) ,putchar ('\n');}
const int N = 1e6 + 10 ;
int n ,ans ,a[N];
signed main (){
n = read ();
up (i ,1, n) {
int l = read () ,r = read ();
a[l] ++ ,a[r + 1] --;
}
int now = 0;
up (i ,0 ,1000000)
now += a[i] ,ans = max (ans ,now);
writeln (ans);
return 0 ;
}当然也可以用树状数组、线段树等数据结构维护,这题正解(最优解)为差分,这些 的就不多讲了。