【POJ】2299 Ultra-QuickSort 树状数组

树状数组求逆序对


WQNMD  long long


Run ID User Problem Result Memory Time Language Code Length Submit Time
17806769 FMM666 2299 Accepted 11496K 969MS G++ 1118B 2017-11-06 15:27:40


#include 
#include 
#include 
#define C (c=nc())
using namespace std;
struct wjnsb
{
	long long x,pla;
}a[500005];
long long ans,n,tr[500005];
inline char nc(void)
{
	static char ch[100010],*p1=ch,*p2=ch;
	return p1==p2&&(p2=(p1=ch)+fread(ch,1,100010,stdin),p1==p2)?EOF:*p1++;
}
inline void read(long long &n)
{
	static char c;long long f=1;n=0;C;
	while (c<'0'||c>'9') c=='-'?f=-1,C:C;
	while (c>='0'&&c<='9') n=(n<<3)+(n<<1)+c-48,C;
	return (void)(n*=f);
}
bool mmp(wjnsb i,wjnsb j){return i.x=1;i-=i&-i) ans+=tr[i];
	return ans;
}
int main(void)
{
	while (1)
	{
		read(n);
		if (n==0) return 0;
		ans=0;
		memset(tr,0,sizeof(tr));
		register long long i;
		for (i=1;i<=n;++i)
			read(a[i].x),a[i].pla=i;
		sort(a+1,a+1+n,mmp);
		for (i=1;i<=n;++i) a[i].x=i;
		sort(a+1,a+1+n,cmp);
		for (i=1;i<=n;++i)
		{
			add(a[i].x);
			ans+=i-query(a[i].x);
		}
		printf("%lld\n",ans);
	}
}


你可能感兴趣的:(POJ,较易,树状数组)