POJ2299

POJ2299 只要理清逆序数的思想,再套上归并算法的模板再注意点 long long sum。不能用int就ok了。

Source Code

Problem: 2299   User: 64162451
Memory: 3820K   Time: 1266MS
Language: C++   Result: Accepted
  • Source Code
  • #include<iostream>
    #include<fstream>
    using namespace std;
    const int N=500005;
    int a[N];
    int t[N];
    long long sum;
    void copy(int *dest,int *src,int b,int e)
    {
    	while(b<=e)
    	{
    		dest[b]=src[b];
    		b++;
    	}
    }
    void merge(int * a,int b,int m, int e)
    {
    	int i=b;
    	int j=m+1;
    	int k=b;
    	while((i<=m)&&(j<=e))
    	{
    		if(a[i]<=a[j])
    			t[k++]=a[i++];
    
    		else
    		{
    			t[k++]=a[j++];
    			sum+=(m-i+1);
    		}
    	}
    	while(i<=m)
    	{
    		t[k++]=a[i++];
    	}
    	while(j<=e)
    	{
    		t[k++]=a[j++];
    	}
    	copy(a,t,b,e);
    }
    void mergesort(int * a,int i,int j)
    {
    		if(i>=j)return;
    		int m=(i+j)/2;
    		mergesort(a,i,m);
    		mergesort(a,m+1,j);
    		merge(a,i,m,j);
    	
    }
    int main()
    {
    	//fstream cin("C:\\Users\\wuyanyisb\\Desktop\\1.txt");
    	int n;
    	while(cin>>n&&n!=0)
    	{
    		sum=0;
    		for(int i=0;i<n;i++)
    			cin>>a[i];
    		mergesort(a,0,n-1);
    		cout<<sum<<endl;
    	}
    	system("pause");
    	return 0;
    }

你可能感兴趣的:(c,算法,user,System,ini,merge)