跳到正文

题解

题解:P11853 [CSP-J2022 山东] 植树节

Fail_Void_Vanish约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
题目
P11853

版本

  1. v1当前

直接上正题。

观察到 1≤l,r≤n1\le l,r\le n(我把题中的 aia_i,bib_i 改为 ll,rr)。

然后就可以差分了。

首先先要确定你会差分。

每次操作 (l,r)\left (l ,r\right ) 在 ll 的位置上加上 11,在 r+1r + 1 的位置上减去 11,维护每个位置的这个值为 aia_i。

然后对于第 ii 个位置,种树的个数即为 ∑i=0nai\sum\limits_{i = 0}^n a_i。

这是差分板子,很好理解,看不懂可以自己搜。

答案即为 max⁡j=0106(∑i=1jai)\max\limits_{j = 0}^{10^6}\left(\sum\limits_{i = 1}^j a_i\right),这个可以前缀和。

时间复杂度为 O(n+V)\mathcal O(n + V),其中 VV 是值域,题目中为 10610^6。

C++
# 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 ;
}

当然也可以用树状数组、线段树等数据结构维护,这题正解(最优解)为差分,这些 O(nlog⁡V+Vlog⁡V)\mathcal O(n\log V + V\log V) 的就不多讲了。

原文