樹狀數組專題(三)POJ2481
//這裏有幾個需要學習的東西.
//1..如何對結構體進行調用排序函數的operator的操作構造
//2..如何把這個題目轉換成爲樹狀數組的思維..
//3..如何去記錄一個數組排序前的位置..在結構體裏面加一個元素記錄原來的位置.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int MN = 110000;
struct Cow
{
int s,e,value;
Cow(){};
bool operator < (const Cow &tmp) const
{
if(e > tmp.e)return 1;
if(e < tmp.e)return 0;
if(e == tmp.e)
{
if(s > tmp.s)return 0;
else return 1;
}
}
};
Cow test[MN];int maxx;
int tree[MN],b[MN],ans[111111],c[MN],exchan[MN];
int Lowbit(int x)
{
return x&(-x);
}
void Updata(int x)
{
if(x <= 0)return;
for(int i = x ; i <= maxx ; i += Lowbit(i))
{
tree[i]++;
}
}
int Getsum(int x)
{
int sum = 0 ;
while(x > 0)
{
sum += tree[x];
x -= Lowbit(x);
}
return sum;
}
int main()
{
int n;
while(scanf("%d",&n) && n != 0)
{
maxx = 0;
memset(tree,0,sizeof(tree));
for(int i = 1 ; i <= n ; i++)
{
scanf("%d%d",&test[i].s,&test[i].e);
test[i].s++;
test[i].value = i;
maxx = max(maxx,test[i].s);
}
sort(test + 1, test + n + 1);
for(int i = 1 ; i <= n ; i++)
{
if(test[i].s == test[i-1].s && test[i].e == test[i-1].e && i > 1)
ans[test[i].value] = ans[test[i-1].value];
else
ans[test[i].value] = Getsum(test[i].s);
Updata(test[i].s);
}
for(int i = 1 ; i <= n ; i++)
{
printf("%d ",ans[i]);
}
printf("\n");
}
}
//1..如何對結構體進行調用排序函數的operator的操作構造
//2..如何把這個題目轉換成爲樹狀數組的思維..
//3..如何去記錄一個數組排序前的位置..在結構體裏面加一個元素記錄原來的位置.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int MN = 110000;
struct Cow
{
int s,e,value;
Cow(){};
bool operator < (const Cow &tmp) const
{
if(e > tmp.e)return 1;
if(e < tmp.e)return 0;
if(e == tmp.e)
{
if(s > tmp.s)return 0;
else return 1;
}
}
};
Cow test[MN];int maxx;
int tree[MN],b[MN],ans[111111],c[MN],exchan[MN];
int Lowbit(int x)
{
return x&(-x);
}
void Updata(int x)
{
if(x <= 0)return;
for(int i = x ; i <= maxx ; i += Lowbit(i))
{
tree[i]++;
}
}
int Getsum(int x)
{
int sum = 0 ;
while(x > 0)
{
sum += tree[x];
x -= Lowbit(x);
}
return sum;
}
int main()
{
int n;
while(scanf("%d",&n) && n != 0)
{
maxx = 0;
memset(tree,0,sizeof(tree));
for(int i = 1 ; i <= n ; i++)
{
scanf("%d%d",&test[i].s,&test[i].e);
test[i].s++;
test[i].value = i;
maxx = max(maxx,test[i].s);
}
sort(test + 1, test + n + 1);
for(int i = 1 ; i <= n ; i++)
{
if(test[i].s == test[i-1].s && test[i].e == test[i-1].e && i > 1)
ans[test[i].value] = ans[test[i-1].value];
else
ans[test[i].value] = Getsum(test[i].s);
Updata(test[i].s);
}
for(int i = 1 ; i <= n ; i++)
{
printf("%d ",ans[i]);
}
printf("\n");
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.