程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> hdu 3743 Frosh Week(離散化+樹狀數組)

hdu 3743 Frosh Week(離散化+樹狀數組)

編輯:關於C語言

Frosh Week

 

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 289    Accepted Submission(s): 72

Problem Description

During Frosh Week, students play various fun games to get to know each other and compete against other teams. In one such game, all the frosh on a team stand in a line, and are then asked to arrange themselves according to some criterion, such as their height, their birth date, or their student number. This rearrangement of the line must be accomplished only by successively swapping pairs of consecutive students. The team that finishes fastest wins. Thus, in order to win, you would like to minimize the number of swaps required.

 

Input

The first line of input contains one positive integer n, the number of students on the team, which will be no more than one million. The following n lines each contain one integer, the student number of each student on the team. No student number will appear more than once.

 

Output

Output a line containing the minimum number of swaps required to arrange the students in increasing order by student number.

 

Sample Input

3 3 1 2

 

Sample Output

2

 

         此題大意:與上題一樣,求逆序數,不要給英文騙到。我想練下寫離散化,所以再寫一次,印象更深刻。

代碼:

Cpp代碼

#include <iostream> 

#include <stdio.h> 

#include <memory.h> 

#include <algorithm> 

using namespace std; 

 

int n, a[1000005]; 

 

struct node 

    int num, id; 

}ch[1000005]; 

 

bool cmp1(node a, node b) 

    return a.num < b.num; 

 

bool cmp2(node a, node b) 

    return a.id < b.id; 

 

int lowbit(int i)  

    return i&(-i); 

 

void update(int i, int x) 

    while(i <= n) 

    { 

        a[i] += x; 

        i += lowbit(i); 

    } 

 

int sum(int i) 

    int sum = 0; 

    while(i > 0) 

    { 

        sum += a[i]; 

        i -= lowbit(i); 

    } 

    return sum; 

 

int main() 

    int i; 

    long long ans;  //注意要long long!!!

    while(scanf("%d", &n) != EOF) 

    { 

        ans = 0; 

        memset(a, 0, sizeof(a)); 

        for(i = 1; i <= n; i++) 

        { 

            scanf("%d", &ch[i].num); 

            ch[i].id = i; 

        } 

        ///離散化

        sort(ch+1, ch+n+1, cmp1);   //按值排序

        ch[1].num = 1;      //直接把他的值改變離散化

        for(i = 2; i <= n; i++) 

        { 

            if(ch[i].num != ch[i-1].num) 

                ch[i].num = i; 

            else ch[i].num = ch[i-1].num; 

        } 

        sort(ch+1, ch+n+1, cmp2);   //再按id排序

        ///離散化完畢

        for(i = 1; i <= n; i++) 

        { 

            update(ch[i].num, 1); 

            ans += (sum(n) - sum(ch[i].num)); 

        } 

        printf("%I64d\n", ans); 

    } 

 

    return 0; 

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