24h購物| | PChome| 登入
2012-04-01 10:47:28| 人氣1,812| 回應0 | 上一篇 | 下一篇

[UVA] 12004 - Bubble Sort

推薦 0 收藏 0 轉貼0 訂閱站台

Bubble Sort 

Check the following code which counts the number of swaps of bubble sort.

int findSwaps( int n, int a[] )
{
    int count = 0, i, j, temp, b[100000];

    for( i = 0; i < n; i++ ) {
        b[i] = a[i];
    }
    for( i = 0; i < n; i++ ) {
        for( j = 0; j < n - 1; j++ ) {
            if( b[j] > b[j+1] ) {
                temp = b[j];
                b[j] = b[j+1];
                b[j+1] = temp;

                count++;
            }
        }
    }
    return count;
}

You have to find the average value of 'count' in the given code if we run findSwaps() infinitely many times using constant 'n' and each time some random integers (from 1 to n) are given in array a[]. You can assume that the input integers in array a[] are distinct.

Input 

Input starts with an integer T ($ le$1000), denoting the number of test cases. Each test case contains an integer n ( 1$ le$n$ le$105) in a single line.

Output 

For each case, print the case number and the desired result. If the result is an integer, print it. Otherwise print it in 'p/q' form, where p and q are relative prime.

Sample Input 

2
1
2

Sample Output 

Case 1: 0
Case 2: 1/2

兩個數字交換的期望值是 1/2
那麼 n 個數字交換的次數為 n(n-1)/2
總共的期望值是 1/2 * n(n-1)/2

#include <stdio.h>
typedef long long Int64;
struct frac {
Int64 num, den;
void print() {
simpler();
if(den != 1)
printf("%lld/%lld\n", num, den);
else
printf("%lld\n", num);;
}
void simpler() {
Int64 g = gcd(num, den);
num /= g;
den /= g;
}
Int64 gcd(Int64 x, Int64 y) {
if(x == 0) return y;
if(y == 0) return x;
Int64 tmp;
while(x%y) {
tmp = x, x = y, y = tmp%y;
}
return y;
}
};
int main() {
int t, Case = 0;
Int64 n;
scanf("%d", &t);
while(t--) {
scanf("%lld", &n);
printf("Case %d: ", ++Case);
frac f = {n*(n-1), 4};
f.print();
}
return 0;
}
 

台長: Morris
人氣(1,812) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][DP] 11258 - String Partition
此分類上一篇:[UVA] 12022 - Ordering T-shirts

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文