zoukankan      html  css  js  c++  java
  • HDU_2523 SORT AGAIN (Hash)

      Hash思想,因为题目要求第K大的数,可能很多人会想到先从小到大排序,然后找到第k个数。但是,注意,|xi - xj|可能会出想重复,也就是说排好序还得处理重复。

    Hash的大体思路是:将|xi - xj|作为一个hash数组的下标,如果hash[|xi - xj|]为空则hash[|xi - xj|]++;查找第k大时直接遍历一遍hash数组就行;

    代码:

    #include <iostream>
    #include
    <cstdio>
    #include
    <cstring>

    using namespace std;

    const int N = 2007;

    int a[N/2];
    int hash[N];

    int abs(int x)
    {
    return x > 0 ? x : -x;
    }
    int main()
    {
    //freopen("data.in", "r", stdin);

    int n, k, T, i, j;
    scanf(
    "%d", &T);
    while(T--)
    {
    scanf(
    "%d%d", &n, &k);
    for(i = 0; i < n; i++)
    scanf(
    "%d", a + i);
    memset(hash,
    0, sizeof(hash));
    int max = -1;
    for(i = 0; i < n-1; i++)
    for(j = i+1; j < n; j++)
    if(!hash[abs(a[i]-a[j])])
    {
    hash[abs(a[i]
    -a[j])]++;
    if(abs(a[i]-a[j]) > max)
    max
    = abs(a[i]-a[j]);
    }
    int cnt = 0;
    for(i = 0; i <= max; i++)
    {
    if(hash[i])
    {
    cnt
    ++;
    if(cnt == k)
    {
    printf(
    "%d\n", i);
    break;
    }
    }
    }
    }
    return 0;
    }
  • 相关阅读:
    WPF的模版
    AvalonDock结合MVVM模式的应用
    A Diagram Designer
    WPF Canvas小例子
    WPF ListView的使用及Linq to XML练习
    httpclient发送接受请求
    json序列化以及反序列化存在多个对象时候的处理
    json序列化
    wpf数据绑定
    wpf之WrapPanel与StackPanel
  • 原文地址:https://www.cnblogs.com/vongang/p/2146961.html
Copyright © 2011-2022 走看看