• Kendall tau距离(即两个内容相同的数组中逆序数对的数量)(算法》P220 第2.5.3.2小节)


         一组排列就是一组N个整数的数组,其中0~N-1的每个数都只出现一次。两个排列之间的 Kendall tau距离就是在两组排列中相对顺序不同的数对的数目。例如,0 3 1 6 2 5 4和1 0 3 6 4 2 5之间的 Kendall tau距离是4,因为0-1、3-1、2-4、5-4这4对数字在两组排列中的相对顺序不同,但其他数字的相对顺序都是相同的。求两个指定数组的Kendall tau距离的代码如下:

    // 如果数组itemsB是有序数组,那么问题就转化为统计数组itemsA中的逆序对(参见《剑指Offer》面试题36)。而在一般情况下,问题可转化为统计数组itemsA中按照数组itemsB中数字的排列顺序确定的逆序对
    int GetKendallTauDistance(int itemsA[], int itemsB[],int length)
    {
    	// 存储 0~N-1 各个数字在数组itemsB中的索引
        int * indexesB = (int *)malloc(length * sizeof(int));
        for (int index = 0; index < length; index++)
    	{
    	    indexesB[itemsB[index]] = index;
    	}
    
    	// 存储数组itemsA中指定索引处的数字在数组itemsB中的索引
        int * indexesA = (int *)malloc(length * sizeof(int));
        for (int i = 0; i < N; i++)
    	{
             indexesA[i] = indexesB[itemsA[i]];
    	}
    
    	// 统计数组indexesA中的逆序对
        int KendallTauDistance = CountInversions(indexesA,length);
    
    	free(indexesB);
    	free(indexesA);
    
    	return KendallTauDistance;
    }
    

      

  • 相关阅读:
    51nod1381 硬币游戏
    51nod1381 硬币游戏
    51nod1384 全排列
    LOJ P10130 点的距离 题解
    POJ P1985 Cow Marathon 题解
    求树的直径(两种方法)
    洛谷 P3518 [POI2011] SEJ-Strongbox 题解
    洛谷 UVA12101 Prime Path 题解
    POJ P2251 Dungeon Master 题解
    POJ P3009 Curling 2.0 题解
  • 原文地址:https://www.cnblogs.com/laifeiyao/p/3475078.html
Copyright © 2020-2023  润新知