POJ - 2481 Cows 树状数组
## POJ - 2481 Cows
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 23766 Accepted: 7987
Description
Farmer John's cows have discovered that the clover growing along the ridge of the hill (which we can think of as a one-dimensional number line) in his field is particularly good.
Farmer John has N cows (we number the cows from 1 to N). Each of Farmer John's N cows has a range of clover that she particularly likes (these ranges might overlap). The ranges are defined by a closed interval [S,E].
But some cows are strong and some are weak. Given two cows: cowi and cowj, their favourite clover range is [Si, Ei] and [Sj, Ej]. If Si <= Sj and Ej <= Ei and Ei - Si > Ej - Sj, we say that cowi is stronger than cowj.
For each cow, how many cows are stronger than her? Farmer John needs your help!
Input
The input contains multiple test cases.
For each test case, the first line is an integer N (1 <= N <= 105), which is the number of cows. Then come N lines, the i-th of which contains two integers: S and E(0 <= S < E <= 105) specifying the start end location respectively of a range preferred by some cow. Locations are given as distance from the start of the ridge.
The end of the input contains a single 0.
Output
For each test case, output one line containing n space-separated integers, the i-th of which specifying the number of cows that are stronger than cowi.
Sample Input
3
1 2
0 3
3 4
0
Sample Output
1 0 0
Hint
Huge input and output,scanf and printf is recommended.
Source
POJ Contest,Author:Mathematica@ZSU
多组输入,给n个线段,计算每个线段被多少个其他线段包含。相同起点和相同终点的不算包含。
把线段按照起点排序,越小的越前面,起点相同则按照重点从小到大排序。
按照排序好的顺序,把线段一条一条加进来。
因为前面的线段起点在当前要加入的这条线段之前,所以包含这条线段的只可能在已加进来的线条中。在已加进来的线段中,判断他们终点是否在当前这条线段之后。
用树状数组\(d\)来存储在\(d[i]\)之前的点有几个,通过\(d[maxn] - d[i-1]\)来计算包含当前线段的条数。
计算完后把当前线段的终点加入\(d\)数组。
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<algorithm>
using namespace std;
struct sen{
int s,e,num;
}a[100001] = {};
bool cmp(sen x,sen y)
{
if (x.s != y.s) return x.s<y.s;
else return x.e>y.e;
}
int lowbit(int x)
{
return x&-x;
}
int main()
{
int n;
while(scanf("%d",&n) && n != 0)
{
sen a[100001] = {};
int c[100001] = {},d[100001] = {};
int maxn = 0;
for (int i = 1;i<=n;i++)
{
scanf("%d%d",&a[i].s,&a[i].e);
a[i].num = i;
maxn = max(maxn,a[i].e);
}
sort(a+1,a+n+1,cmp);
for (int i = 1;i<=n;i++)
{
if (a[i].s == a[i-1].s && a[i].e == a[i-1].e) c[a[i].num] = c[a[i-1].num];//如果两条线段相同,则包含数一样
else//计算包含多少个
{
int x = maxn,sum = 0;
while (x > 0)
{
sum+=d[x];
x -= lowbit(x);
}
x = a[i].e - 1;
while (x>0)
{
sum-=d[x];
x-= lowbit(x);
}
c[a[i].num] = sum;
}
int x = a[i].e;//更新
while (x <= maxn)
{
d[x]++;
x += lowbit(x);
}
}
printf("%d",c[1]);
for (int i = 2;i<=n;i++) printf(" %d",c[i]);
printf("\n");
}
}
蒟蒻的线段树学习之旅开始了orz
本文来自博客园,作者:Un-Defined,转载请保留本文署名Un-Defined,并在文章顶部注明原文链接:https://www.cnblogs.com/EIPsilly/p/15606196.html