zoukankan      html  css  js  c++  java
  • 「UVA12004」 Bubble Sort 解题报告

    UVA12004 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 (≤ 1000), denoting the number of test cases. Each test case contains an integer n (1 ≤ n ≤ 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
    

    思路

    一句话题意:求长度为n的排列的期望逆序对数。

    很简单,(f(n)=f(n-1)+frac{n-1}2=frac{n imes(n-1)}4,f(1)=0)

    为什么呢?假设把(n)插入长度((n-1))的排列,有(n)种方法。期望增加的逆序对数就是(frac{1+2+...n-1}n=frac{n imes (n-1)}{2n}=frac{n-1}2)

    所以(f(n)=f(n-1)+frac{n-1}2)

    很简单吧?别忘了开long long

    代码

    #include<bits/stdc++.h>
    using namespace std;
    #define LL long long
    
    int T, i;
    LL n;
    
    int main(){
    	scanf( "%d", &T );
    	for ( int i = 1; i <= T; ++i ){
    		scanf( "%lld", &n );
    		n = n * ( n - 1 ) / 2;
    		if ( n & 1 ) printf( "Case %d: %lld/2
    ", i, n );
    		else printf( "Case %d: %lld
    ", i, n / 2 );
    	}
    	return 0;
    }
    
    
  • 相关阅读:
    git this exceeds GitHub's file size limit of 100.00 MB
    使用vue-cli创建vue工程
    【转】Visual Studio Code必备插件
    linux安装openssl
    Centos7离线安装mysql8
    使用nmon来按频率采集数据
    Mac下编译android4.0.4遇到的问题
    32位ubuntu16.4编译android4.1.1
    vmvare安装vmtools菜单灰色
    Substrate 使用
  • 原文地址:https://www.cnblogs.com/louhancheng/p/10271232.html
Copyright © 2011-2022 走看看