[树状数组]poj2481 Cows

来源:互联网 发布:企业在淘宝开店 编辑:程序博客网 时间:2024/05/17 10:43

poj2481 Cows, 题目链接

题意:

好吧又是熟悉的牛,一条河岸,每只牛都有吃草范围[S,E],它们或强壮或虚弱。我们这样定义强壮:牛i和牛j,它们的吃草范围分别是[Si,Ei]和[Sj,Ej],如果Si<=Sj && Ei>=Ej && Ei-Ej>Ej-Sj,这样我们就说牛i比牛j强壮,注意如果吃草范围完全一样那么它们之间不存在强弱之分,本题求的是每只牛比他们强壮的牛的数量

思路:

和我在模板中引之为例的hdu2352 Stars一样还是降维,只不过这次改成求左上角
y降序排列,y一样则x升序排列,注意不能是同一个点

代码:

#include <iostream>#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;#define lowbit(x) (x&(-x))const int N = 1e5+5;int tree[N];int f[N];int n, s, e;struct node{    int s;    int e;    int id;}tot[N];bool cmp(const node &x, const node &y){    if(x.e==y.e)        return x.s<y.s;    return x.e>y.e;}void update(int k){    while(k <= n){        tree[k]++;        k += lowbit(k);    }}int sum(int k){    int re=0;    while(k>0){        re += tree[k];        k -= lowbit(k);    }    return re;}int main(){    while(scanf("%d", &n) && n){        memset(tree,0,sizeof(tree));        memset(f,0,sizeof(f));        for(int i=0; i<n; i++){            scanf("%d%d", &tot[i].s, &tot[i].e);            tot[i].id = i;        }                sort(tot,tot+n,cmp);        for(int i=0; i<n; i++){            f[tot[i].id] = sum(tot[i].s+1);            if(tot[i].s==tot[i-1].s && tot[i].e==tot[i-1].e)                f[tot[i].id] = f[tot[i-1].id];            update(tot[i].s+1);        }        for(int i=0; i<n-1; i++)            printf("%d ", f[i]);        printf("%d\n", f[n-1]);    }    return 0;}


反思:

我的代码 2640K 2235MS,真是渣呀,看到第一是2300K 204MS,很好奇同样是G++怎么可以这么快……

看discuss中说试一试快速读入/读入优化?搜了一下也不是很懂,先贴上代码日后再看……

//输入外挂void nextInt(int &x){    do        c=getchar();    while (c<'0'||c>'9');    x=c-'0';    while('0'<=(c=getchar())&&c<='9')        x=x*10+c-'0';}inline void scan_d(int &ret) {      char c; ret=0;      while((c=getchar())<'0'||c>'9');      while(c>='0'&&c<='9') ret=ret*10+(c-'0'),c=getchar();  }



0 0
原创粉丝点击