PAT 1046. Shortest Distance

来源:互联网 发布:禁用445端口 编辑:程序博客网 时间:2024/05/22 15:59

呵,这不是一篇题解呵呵。一道20分的水题,我用了树状数组,过了以后再看看别人的码子,根本就不用树状数组啊呵呵,而且我现在已经不懂树状数组存在的意义了,如果一开始就已经算好了S1,S2,S3……Sn,那么数列从第i加到第j之和就等于(Sj+1 - Si),根本就不用树状数组啊(╯‵□′)╯︵┻━┻

#include<cstdio>#include<cstring>#include<iostream>using namespace std;int tree[100005],n;int inpu[100005];int calcu(int x){int re=0;while(x>0){re+=tree[x];x-=(x&-x);}return re;}int func(int a,int b){int temp;if(a>b){temp=a;a=b;b=temp;}int re1,re2;re1=calcu(b-1)-calcu(a-1);re2=calcu(n)-re1;return (re1<re2)?re1:re2;}int main(){int i,temp;memset(tree,0,sizeof(tree));scanf("%d",&n);for(i=1;i<=n;i++){scanf("%d",&inpu[i]);temp=i;while(temp<=n){tree[temp]+=inpu[i];temp+=(temp&-temp);}}int m,u,v;scanf("%d",&m);while(m--){scanf("%d%d",&u,&v);printf("%d\n",func(u,v));}return 0;}


0 0
原创粉丝点击