程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> NYOJ 233 &&NYOJ 322 Sort(樹狀數組)

NYOJ 233 &&NYOJ 322 Sort(樹狀數組)

編輯:C++入門知識

NYOJ 233 &&NYOJ 322 Sort(樹狀數組)


鏈接:click here

題意:

描述 You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
輸入The input consists of T number of test cases.(<0T<1000) Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.輸出For each case, output the minimum times need to sort it in ascending order on a single line.樣例輸入
2
3
1 2 3
4
4 3 2 1
樣例輸出
0
6
思路:就是求一組數據的逆序數,樹狀數組求法,不解釋:

代碼:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;
#define lowbit(a) a&-a
#define Max(a,b) a>b?a:b
#define Min(a,b) a>b?b:a
#define mem(a,b) memset(a,b,sizeof(a))
int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
const double eps = 1e-6;
const double Pi = acos(-1.0);
static const int inf= ~0U>>2;
static const int maxn =110;
int  h[1000001],w[100],Map[200];
int m[10001], N;
void Add(int i)
{
    while(i<=1001)
    {
        m[i]++;
        i+=lowbit(i);
    }
}
int Sum(int i)
{
    int res=0;
    while(i>0)
    {
        res+=m[i];
        i-=lowbit(i);
    }
    return res;
}
int main()
{
    int T,temp;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&N);
        memset(m,0,sizeof(m));
        int ans=0;
        for(int i=1; i<=N; i++)
        {
            scanf("%d",&temp);
            Add(temp);
            ans+=(i-Sum(temp));
        }
        printf("%d\n",ans);
    }
    return 0;
}
When you want to give up, think of why you persist until now


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved