hdu1800(哈希)

Flying to the Mars

题意:

  给出n个人的教育水平,水平高的人可以教水平低的人,每个人最多只能有一个老师,同时也最多只能有一个学生(没有老师或者没有学生也是合法的),把位于一条链上的所有人定义为一组(比如A是B的老师,B是C的老师,那么A,B,C为一组),问最少需要多少组?

分析:

  如果n个人的教育水平排序后是严格单调的话,很明显可以直接分在一个组里面。如果出现重复,假设为n,考虑到相同的数不能出现在同一个组,所以我们至少需要n组。考虑采用对于每一组每次都挑选出最多的不同的数字的贪心策略,不难看出我们需要的最少组数就是教育水平的最大重复次数。

代码:

#include <stack>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;
#define ll long long
#define ull unsigned long long
#define cls(x) memset(x,0,sizeof(x))
#define clslow(x) memset(x,-1,sizeof(x))

const int maxn=249997;

int n;

char s[40];
int Hash[maxn];

unsigned int BKDRHash(char* s)
{
    unsigned int seed=131;
    unsigned int hashvalue=0;
    //处理前导0,否则的话0123和123会产生不同的hash值
    while(*s=='0')  s++;
    while(*s)
    {
        hashvalue=hashvalue*seed+(*s++);
    }
    return hashvalue%maxn;
}

int main()
{
//    freopen("in.txt","r",stdin);
    while(scanf("%d",&n)!=EOF)
    {
        cls(Hash);
        int ans=0;
        for(int i=1;i<=n;i++){
            scanf("%s",s);
            int key=BKDRHash(s);
            Hash[key]++;
            ans=max(ans,Hash[key]);
        }
        printf("%d\n",ans);
    }
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/shutdown113/p/9384413.html