P3660 Why Did the Cow Cross the Road 讲解
mairuisheng · · 算法·理论
-
题目: P3660 [USACO17FEB] Why Did the Cow Cross the Road III G
-
题目大意: 数字
1\sim n ,其中数字i 第一次、第二次出现的下标分别为a_i ,b_i 。满足a_i<a_j<b_i<b_j 的(i,j) 即为交叉对。求交叉对的数量。 -
方法一:暴力
50pts。 -
方法二:树状数组
将
[a_i,a_j] ,[b_i,b_j] 视为一个区间,如果区间[a_i,a_j] ,[b_i,b_j] 有重叠,那么(i,j) 即为交叉对。先按区间左端点排序,依次枚举所有区间,将区间右端点插入树状数组。和区间
j 有重叠的区间数量,即为查询区间j 里已插入的区间右端点数量。
::::info[AC code]
//#pragma GCC optimize(3)
#include<cstdio>
#include<algorithm>
using namespace std;
inline int read()
{
int x=0,f=1;
char s;
s=getchar();
while(s<48||s>57)
{
if(s=='-')f=-f;
s=getchar();
}
while(s>47&&s<58)
{
x=(x<<3)+(x<<1)+(s-48);
s=getchar();
}
return x*f;
}
const int N=5e4+1;
int n;
pair<int,int> a[N<<1];
int sum[N<<1];
long long ans,ans2;
int lowbit(int x)
{
return x&-x;
}
void update(int x,int v)
{
for(;x<=n<<1;x+=lowbit(x))sum[x]+=v;
}
int query(int x)
{
int res=0;
for(;x;x-=lowbit(x))res+=sum[x];
return res;
}
int main()
{
n=read();
int i,j,x;
for(i=1;i<=n<<1;++i)
{
x=read();
if(!a[x].first)a[x].first=i;
else a[x].second=i;
}
sort(a+1,a+1+n);
for(i=1;i<=n;++i)
{
ans+=query(a[i].second-1)-query(a[i].first);//查询已插入的区间右端点数量
update(a[i].second,1);//插入右端点
}
printf("%lld",ans);
return 0;
}
::::
- 致谢:部分借鉴题解
0426 sol。