2041.干草堆 (差分)
题目链接
https://www.acwing.com/problem/content/2043/
思路
差分思想
用A数组存下所有数,B数组存下两个数之间的差,则:
给区间[l, r]中的每个数加上c:B[l] += c, B[r + 1] -= c
例:
A[]={4,2,6,1,5,3},则B[]={4,-2,4,-5,4,-2}
此时A[i]=B[0]+B[1]+..B[i]
给区间[2,4]加2时
A[]={4,2,8,3,7,3}
B[]={4,-2,6,-5,4,-4}
因为差分时区间同时增减,所以差分不会变,只要求端点处和未被加减的数即可得出结果。
AC代码
#include <algorithm>
#include <iostream>
using namespace std;
int n;
int k;
//给区间[l, r]中的每个数加上c:B[l] += c, B[r + 1] -= c
int a[1000005];
int main(int argc, char* argv[])
{
cin >> n >> k;
for(int i=0;i<k;i++)
{
int t1, t2;
cin >> t1 >> t2;
a[t1]++;
a[t2 + 1]--;
}
for(int i=1;i<=n;i++)
{
a[i] += a[i - 1];
}
nth_element(a + 1, a+n / 2 + 1, a + n + 1);
cout << a[n / 2 + 1];
return 0;
}
心得
以为是简单题,结果超时了,寄!