标签:
这种问题先对区间和线段进行排序,排序方法见代码cmp
然后分析其中一个点,用sum求值
poj 3067
Description
Input
Output
Sample Input
1 3 4 4 1 4 2 3 3 2 3 1
Sample Output
Test case 1: 5
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<string> #include<algorithm> #define LL long long #define inf 0x3f3f3f3f using namespace std; struct line { int x,y; }q[1000100]; int c[1010]; int cmp(line a,line b) { if(a.x==b.x) return a.y>b.y; return a.x>b.x; } int n,m,k; int lowbit(int x) { return x&(-x); } void add(int x,int val)//下标为x值增加val { while(x<=m) { c[x]+=val; x+=lowbit(x); } } int sum(int x)//求下标1~x的数组之和 { int ans=0; while(x>0) { ans+=c[x]; x-=lowbit(x); } return ans; } int main() { int T; cin>>T; int kase=1; while(T--) { scanf("%d%d%d",&n,&m,&k); for(int i=0;i<=k-1;i++) scanf("%d%d",&q[i].x,&q[i].y); sort(q,q+k,cmp); memset(c,0,sizeof(c)); LL cnt=0; for(int i=0;i<=k-1;i++) { cnt+=sum(q[i].y-1); add(q[i].y,1); } cout<<"Test case "<<kase++<<": "<<cnt<<endl; } return 0; }
poj 2481
Description
Input
Output
Sample Input
3 1 2 0 3 3 4 0
Sample Output
1 0 0
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<string> #include<algorithm> #define LL long long #define inf 0x3f3f3f3f using namespace std; int c[100010]; int num[100010]; struct node { int id; int l,r; }q[100010]; int cmp(node a,node b) { if(a.r==b.r) return a.l<b.l; return a.r>b.r; } int lowbit(int x) { return x&(-x); } void add(int x,int val)//下标为x值增加val { while(x<=100000)//n是数组的规模,容易出错 { c[x]+=val; x+=lowbit(x); } } int sum(int x)//求下标1~x的数组之和 { int ans=0; while(x>0) { ans+=c[x]; x-=lowbit(x); } return ans; } int main() { int n; while(cin>>n) { if(n==0) return 0; for(int i=0;i<=n-1;i++) { scanf("%d%d",&q[i].l,&q[i].r); q[i].id=i; } sort(q,q+n,cmp); memset(c,0,sizeof(c)); for(int i=0;i<=n-1;i++) { if(q[i].l==q[i-1].l&&q[i].r==q[i-1].r&&i!=0) num[q[i].id]=num[q[i-1].id]; else num[q[i].id]=sum(q[i].l+1); add(q[i].l+1,1); } for(int i=0;i<=n-2;i++) cout<<num[i]<<" "; cout<<num[n-1]<<endl; } return 0; }
poj 3067 poj 2481 树状数组变形+对区间排序
标签:
原文地址:http://blog.csdn.net/winycg/article/details/51355467