标签:
Description
Input
Output
Sample Input
Sample Output
# include<cstdio> # include<iostream> using namespace std; # define MAX 5004 # define inf 99999999 # define lid id<<1 # define rid id<<1|1 struct Segtree { int l,r; int sum; }tree[MAX*4]; int a[MAX]; void push_up( int id ) { tree[id].sum = tree[lid].sum+tree[rid].sum; } void build ( int id,int l,int r ) { tree[id].l = l; tree[id].r = r; tree[id].sum = 0; if ( l==r ) { return; } int mid = ( tree[id].l+tree[id].r )/2; build ( lid,l,mid); build ( rid,mid+1,r); push_up(id); } void update( int id,int x,int val ) { if ( tree[id].l==tree[id].r ) { tree[id].sum = 1; return; } int mid = ( tree[id].l+tree[id].r )/2; if ( x<=mid ) update(lid,x,val); else update(rid,x,val); push_up(id); } int query( int id,int l,int r ) { if ( tree[id].l==l&&tree[id].r==r ) { return tree[id].sum; } int mid = ( tree[id].l+tree[id].r )/2; if ( r <= mid ) return query(lid,l,r); else if ( l > mid ) return query(rid,l,r); else { return query(lid,l,mid)+query(rid,mid+1,r); } } int main(void) { int n; while ( scanf("%d",&n)!=EOF ) { for ( int i = 0;i < n;i++ ) scanf("%d",&a[i]); build(1,0,n-1); int sum = 0; for ( int i = 0;i < n;i++ ) { if( a[i]!=n-1 ) { sum+= query(1,a[i]+1,n-1); update(1,a[i],1); } else { sum+=query(1,a[i],n-1); update(1,a[i],1); } } int ans = inf; ans = min(ans,sum); for ( int i = 0;i < n;i++ ) { sum-=a[i]; sum+=n-1-a[i]; ans = min(ans,sum); } printf("%d\n",ans); } return 0; }
HDU 1394 Minimum Inversion Number (线段树,单点更新)
标签:
原文地址:http://www.cnblogs.com/wikioibai/p/4741139.html