//解法2:按Si值做降序排序后,相当于求每个位置i左边大于等于E[i]的个数 //树状数组更新节点的路径和求和的路径要改变,getSum(i) 相当于求i+(i+1)+...+MAXN #include <iostream> #include <algorithm> using namespace std; const int MAXN = 100010; int sum[MAXN]; struct Cow { int s; int e; int id; int val; }cow[MAXN]; bool cmp1(const struct Cow a, const struct Cow b) { if(a.s == b.s) { return a.e > b.e; } return a.s < b.s; } bool cmp2(const struct Cow a, const struct Cow b) { return a.id < b.id; } int lowbit(int x) { return x&(-x); } //更新节点的路径改变 void update(int x, int val) { for(int i=x; i>0; i-=lowbit(i)) { sum[i] += val; } } //求和的路径改变 sum[4] = num[4]+num[5]+num[6]+num[7] ,sum[2]=num[2]+num[3].... int getSum(int x) { int s = 0; for(int i=x; i<MAXN; i+=lowbit(i)) { s += sum[i]; } return s; } int main() { int n; while(cin>>n,n) { memset(sum,0,sizeof(sum)); for(int i=0; i<n; i++) { scanf("%d%d",&cow[i].s,&cow[i].e); cow[i].s++; cow[i].e++; cow[i].id = i; } sort(cow,cow+n,cmp1); cow[0].val = 0; update(cow[0].e,1); for(int i=1; i<n; i++) { if(cow[i].s == cow[i-1].s && cow[i].e == cow[i-1].e) { cow[i].val = cow[i-1].val; } else { cow[i].val = getSum(cow[i].e); } update(cow[i].e,1); } sort(cow,cow+n,cmp2); for(int i=0; i<n-1; i++) { cout<<cow[i].val<<" "; } cout<<cow[n-1].val<<endl; } return 0; }
// poj 2481 树状数组.cpp : 定义控制台应用程序的入口点。//题目要得到满足Si <= Sj and Ei >= Ej and Ei-Si > Ej-Sj (Si!=Sj && Ei!=Ej) 的个数//解法1:若按Ei值升序排序后,则相当于求每个位置i左边小于等于S[i]的个数.解法2:按Si值做降序排序后,相当于求每个位置i左边大于等于E[i]的个数 树状数组更新节点的路径和求和的路径要改变,getSum(i) 相当于求i+(i+1)+...+MAXN #include <iostream> #include <algorithm> using namespace std; const int MAXN = 100010; int sum[MAXN]; struct Cow { int s; int e; int id; int val; }cow[MAXN]; bool cmp1(const struct Cow a, const struct Cow b) { if(a.s == b.s) { return a.e > b.e; } return a.s < b.s; } bool cmp2(const struct Cow a, const struct Cow b) { return a.id < b.id; } int lowbit(int x) { return x&(-x); } //更新节点的路径改变 void update(int x, int val) { for(int i=x; i>0; i-=lowbit(i)) { sum[i] += val; } } //求和的路径改变 sum[4] = num[4]+num[5]+num[6]+num[7] ,sum[2]=num[2]+num[3].... int getSum(int x) { int s = 0; for(int i=x; i<MAXN; i+=lowbit(i)) { s += sum[i]; } return s; } int main() { int n; while(cin>>n,n) { memset(sum,0,sizeof(sum)); for(int i=0; i<n; i++) { scanf("%d%d",&cow[i].s,&cow[i].e); cow[i].s++; cow[i].e++; cow[i].id = i; } sort(cow,cow+n,cmp1); cow[0].val = 0; update(cow[0].e,1); for(int i=1; i<n; i++) { if(cow[i].s == cow[i-1].s && cow[i].e == cow[i-1].e) { cow[i].val = cow[i-1].val; } else { cow[i].val = getSum(cow[i].e); } update(cow[i].e,1); } sort(cow,cow+n,cmp2); for(int i=0; i<n-1; i++) { cout<<cow[i].val<<" "; } cout<<cow[n-1].val<<endl; } return 0; }
poj 2481 树状数组
最新推荐文章于 2019-10-04 21:38:42 发布