Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

线段树代码 仅供参考

Posted by soledada_ at 2013-11-26 18:43:14 on Problem 2299
#include <iostream>
#include <set>
using namespace std;
#define SIZE 501000
struct Data{
	int value,idx;
};
bool operator <(Data d1,Data d2)
{
	if(d1.value==d2.value)
		return d1.idx<d2.idx;
	else
		return d1.value<d2.value;
}

struct Node{
	int l,r,v;
};
Node node[SIZE*3];
int data[SIZE];
int n;

void init(int v,int l,int r)
{
	node[v].l=l;
	node[v].r=r;
	if(l==r)
	{
		node[v].v=1;
		return ;
	}
	int mid=(l+r)/2;
	init(v*2,l,mid);
	init(v*2+1,mid+1,r);
	node[v].v=node[v*2].v+node[v*2+1].v;
}
int query(int v,int l,int r)
{
	if(node[v].l == l && node[v].r == r)
	{
		return node[v].v;
	}
	int mid=(node[v].l+node[v].r)/2;

	if(l>mid)
		return query(v*2+1,l,r);
	else if(r<=mid)
		return query(v*2,l,r);
	else
	{
		return query(v*2,l,mid)+query(v*2+1,mid+1,r);
	}
}
void sub(int v,int idx)
{
	node[v].v--;
	if(node[v].l==node[v].r && node[v].l==idx)
	{
		return ;
	}
	int mid=(node[v].l+node[v].r)/2;
	if(idx<=mid)
		sub(v*2,idx);
	else
		sub(v*2+1,idx);
}

set<Data>st;
int main()
{
	while(scanf("%d",&n) && n!=0)
	{
		st.clear();
		int i;
		for(i=1;i<=n;i++)
		{
			scanf("%d",&data[i]);
			Data dt;
			dt.value=data[i];
			dt.idx=i;
			st.insert(dt);
		}
		init(1,1,n);

		__int64 ans=0;
		set<Data>::iterator it;
		for(it=st.begin();it!=st.end();it++)
		{
			if(it->idx==1)
			{
				sub(1,it->idx);//还是得删除
				continue;
			}
            ans+=query(1,1,it->idx - 1);
			sub(1,it->idx);
		}
		printf("%I64d\n",ans);

	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator