又见余数

来源:互联网 发布:航海家软件指标公式 编辑:程序博客网 时间:2024/05/22 00:17

链接:http://exam.upc.edu.cn/problem.php?id=1819

题意:n头奶牛,各有一个编号a[i]。奶牛会自己寻找房间号为a[i] % k。k个房间,房间号为0……k-1.保证没有任何两个奶牛住在一个房间中时,至少需要多少个房间。

解析:题解的关键就是如果任意两个点的差是l,或者是l的倍数。那么这两个点余l一定是相等的。利用类似素数筛选法的方法。

先对奶牛的编号进行排序,计算出任意两个奶牛之间的差值(先排序,计算时就不会出现负数了),对所有差值数标记为1.从n开始枚举房间数(n头奶牛至少n个房间),如果是成立的,就继续枚举房间数的倍数是否是差值数。

#include <iostream>#include <cstdio>#include <cstring>#include <sstream>#include <string>#include <algorithm>#include <list>#include <map>#include <vector>#include <queue>#include <stack>#include <cmath>#include <cstdlib>using namespace std;int a[5005];int d[1000005];int main(){    //freopen("in.txt","r",stdin);    int n;    scanf("%d",&n);    for(int i = 0; i < n; i ++)    {        scanf("%d",&a[i]);    }    int maxn = 0;    for(int i = 0; i < n; i ++)    {        for(int j =  i + 1; j < n; j ++)        {            maxn = max(maxn,a[j] - a[i]);            d[a[j] - a[i]] = 1;        }    }    int p;    int ans;    for(int l = n ;;l ++)    {         bool flag = false;        if(d[l])            continue;        p = l * 2;        while(p <= maxn)        {              if(d[p])              {                  flag = true;                  break;              }            p += l;         }        if(flag == false)        {             ans = l;            break;        }    }    printf("%d\n",ans);    return 0;}


代码:

0 0
原创粉丝点击