51nod 1495 中国好区间 详细题解(尺取+前缀和)

来源:互联网 发布:淘宝发布宝贝照片尺寸 编辑:程序博客网 时间:2024/05/29 21:33


阿尔法在玩一个游戏,阿尔法给出了一个长度为n的序列,他认为,一段好的区间,它的长度是>=k的,且该区间的第k大的那个数,一定大于等于T。那么问题来了,阿尔法想知道有多少好的区间。

由于阿尔法的序列长度实在是太大了,无法在规定时间内读入。

他想了一个绝妙的方法。

读入a[0],b,c,p,则a[i]=(a[i-1]*b+c)mod p。


样例解释:

a1~a5分别为47,135,247,35,147

对应的7个区间分别为[1,3],[2,3],[1,4],[2,4],[1,5],[2,5],[3,5]



对于重复的数字1,2,2 第一大是2,第二大也是2,第三大是1。
Input
读入一行,7个数字,表示n(n<=10000000),k(k<=n),T,a[0],b,c,p。所有数字均为正整数且小于等于10^9。
Output
输出一行表示好区间的个数。
Input示例
5 2 100 10 124 7 300
Output示例
7

思路:第K大的,就是从大到小第k个数,我们输入的时候,做一个预处理,记录前i个区间有几个比t大的,然后尺取,因为区间 >=k,所以一开始s = 1, e = k,尺取前缀和找这个区间有k个比t大的数,那么这个区间往后所有的区间都是符合要求的。。。 然后移动前端点。。。

#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>using namespace std;const int maxn = 1e7 + 5;typedef long long ll;ll sum[maxn], n, k, t, a, b, c, p;ll ans = 0;int main(){    while(cin >> n >> k >> t >> a >> b >> c >> p)    {//        memset(sum, 0, sizeof(sum));        for(int i = 1; i <= n; i++)        {            a = (a*b+c)%p;            if(a >= t) sum[i] = sum[i-1]+1;            else sum[i] = sum[i-1];        }        ll s = 1, e = k;        ans = 0;        while(1)         {            while(sum[e]-sum[s-1] < k && e <= n) e++;            if(e > n) break;//            while(sum[e]-sum[s-1] >= k) s++;//            ans += s-1;            ans += n-e+1;            s++;        }        cout << ans << endl;    }    return 0;}

如果枚举后端点容易写错。。错误代码:

#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>using namespace std;const int maxn = 1e7 + 5;typedef long long ll;ll sum[maxn], n, k, t, a, b, c, p;ll ans = 0;int main(){    while(cin >> n >> k >> t >> a >> b >> c >> p)    {        for(int i = 1; i <= n; i++)        {            a = (a*b+c)%p;            if(a >= t) sum[i] = sum[i-1]+1;            else sum[i] = sum[i-1];        }        ll s = 1, e = k;        ans = 0;        while(1)        {            while(sum[e]-sum[s-1] < k && e <= n) e++;            if(e > n) break;            while(sum[e]-sum[s-1] >= k) s++;            ans += s-1;//            ans += n-e+1;//            s++;        }        cout << ans << endl;    }    return 0;}

正确代码:

#include<iostream>using namespace std;int s[10000002];int main(){    long long n,k,t,a,b,c,p;    cin>>n>>k>>t>>a>>b>>c>>p;    s[0]=0;    for(int i=1;i<=n+1;i++)    {        s[i]=s[i-1];        if(a>=t)s[i]++;        a=(a*b+c)%p;    }    long long beg=0,end=k,ans=0;    while(s[end]-s[beg]<k)end++;    while(end<=n+1)    {        while(s[end]-s[beg+1]>=k)beg++;        ans+=beg;        end++;     }    cout<<ans<<endl;    return 0;}


1 0