差分序列是一种基于前缀和数组的神奇算法,在Rivendell神的教导下,我学会了这种神奇算法,先贴出Rivendell神博客的网址
http://www.cnblogs.com/Rivendell
我们考虑这样一种问题,对于区间内每一组修改,修改范围是连续的,那么基于这种特性,我们可以对它的区间首段加上x,再在区间末端+1处减去x,最终用前缀和数组加以统计,那么有且仅有这一段区间的值就整体赋为了x(由于开头加了x,所以区间值开始修改,直到末端+1处-x,对之后的数据也不会有任何影响)。就可以得出所需的值。(此处若不明白,模拟一下就明白喽。。。)
先粘出模版题 COGS 1435 金发姑娘与N头牛 code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct hp{
int l,r;
}a[20001];
int b[40001],dc[20001];
int s[50000],n;
int main()
{
int i,size,maxn,x,y,z;
freopen("milktemp.in","r",stdin);
freopen("milktemp.out","w",stdout);
scanf("%d%d%d%d",&n,&x,&y,&z);
for (i=1;i<=n;++i)
{
scanf("%d%d",&a[i].l,&a[i].r);
b[i<<1-1]=a[i].l;
b[i<<1]=a[i].r;
}
sort(b+1,b+2*n+1);
size=unique(b+1,b+2*n+1)-b-1;
for (i=1;i<=n;++i)
{
a[i].l=upper_bound(b+1,b+size+1,a[i].l)-b;
a[i].r=upper_bound(b+1,b+size+1,a[i].r)-b;
}
size+=2;
for (i=1;i<=n;++i)
{
dc[0]+=x;
dc[a[i].l]-=x; dc[a[i].l]+=y;
dc[a[i].r+1]-=y; dc[a[i].r+1]+=z;
dc[size]-=z;
}
maxn=0;
s[0]=dc[0];
for (i=1;i<=size;++i)
{
s[i]=s[i-1]+dc[i];
maxn=max(maxn,s[i]);
}
printf("%d\n",maxn);
fclose(stdin);
fclose(stdout);
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- COGS 465 挤牛奶 一道看似很水的差分序列(只有一星),当由于题目中有关开闭区间交代的很不明确,所以乱搞了几次,终于AC了。。。。。。
我们建两个前缀和数组,分别保存挤奶时间与空闲时间,然后差分约束,最后统计:对于挤奶的数组,统计>0的连续最长子区间;对与空闲时间的前缀和数组,统计>n-1的连续最长子区间;输出即可;但这样只能A九个点,我们发现,这坑爹的数据居然认为1~100与101~200不连续,于是我们考虑把区间扩大,原先的1~100变为2~200,原先的101~200变为202~400,这样就不连续了,处理出答案再除去二就好了。 code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct hp{
int l,r;
}a[5001];
int dcb[2000001],dcw[2000001];
int sb[2000001],sw[2000001];
int n;
int main()
{
int i,size,maxn,minn;
int ansb,answ,sum;
freopen("milk2.in","r",stdin);
freopen("milk2.out","w",stdout);
scanf("%d",&n);
minn=2100000000; maxn=0;
for (i=1;i<=n;++i)
{
scanf("%d%d",&a[i].l,&a[i].r);
a[i].l*=2; a[i].r*=2;
minn=min(minn,a[i].l);
maxn=max(maxn,a[i].r);
}
for (i=1;i<=n;++i)
{
dcb[a[i].l]++;
dcb[a[i].r+1]--;
dcw[minn]++;
dcw[a[i].l+1]--;
dcw[a[i].r]++;
dcw[maxn+1]--;
}
for (i=minn;i<=maxn+1;++i)
sb[i]=sb[i-1]+dcb[i];
for (i=minn;i<=maxn+1;++i)
sw[i]=sw[i-1]+dcw[i];
sum=0; ansb=0; answ=0;
for (i=minn;i<=maxn+1;++i)
{
if (sb[i]>0)
sum++;
else
sum=0;
ansb=max(ansb,sum);
}
sum=0;
for (i=minn;i<=maxn+1;++i)
{
if (sw[i]>n-1)
sum++;
else
sum=0;
answ=max(answ,sum);
}
printf("%d %d\n",(ansb-1)/2,(answ-1)/2);
fclose(stdin);
fclose(stdout);
return 0;
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Lcomyn