鱼C论坛

 找回密码
 立即注册
查看: 2597|回复: 1

一个蛮力搜索的问题,缠了我好久

[复制链接]
发表于 2014-2-1 20:31:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 andalousie 于 2014-2-1 20:32 编辑

我有个不太好的习惯,就是喜欢在全局一下儿把所有的变量声明完,其实有些变量在局部何以发挥作用。
这是一个找出假金币的算法。
输入示例
  1. 5 3
  2. 2 1 2 3 4
  3. <
  4. 1 1 4
  5. =
  6. 1 2 5
  7. =
复制代码
输出3
  1. #include <iostream>

  2. bool jd(int j, int *s, char c)
  3. {
  4.   //Assuming that the j-th coin is fake
  5.   //and check the correctness of this hypothesis
  6.   //s is the weighing record, the first element is number of counterweight
  7.   //c is the result
  8.   int i, f;
  9.   int m = s[0] << 1;
  10.   for(i=f=1; i<=m && f; )
  11.   {
  12.     if(s[i] == j)
  13.       f = 0;
  14.     else
  15.       ++i;
  16.   }
  17.   //Judging whether coin j is included
  18.   if((!f && c == '=') || (f && c != '='))
  19.     return 0;
  20.   return 1;
  21. }

  22. int main()
  23. {
  24.   int num[100][1001];
  25.   char s[1000];                       //Input
  26.   int i, t, n, k, no, j;
  27.   std::cin >> n >> k;
  28.   for(i=0; i<k; ++i)
  29.   {
  30.     std::cin >> num[i][0];
  31.     for(j=1; j<=2*num[i][0]; ++j)
  32.       std::cin >> num[i][j];
  33.     std::cin.get();
  34.     std::cin >> s[i];
  35.   }

  36.   for(i=0, t=0; i<=n; ++i)            //Search all the cases
  37.   {
  38.     for(j=0; j<k && jd(i, num[j], s[j]); ++j);
  39.                                       //Check
  40.     if(j < k) continue;
  41.     ++t;                              //t stores the possible cases
  42.     if(t > 1) break;
  43.     no = i;                           //not only one fake coin
  44.   }

  45.   if(t != 1)
  46.     std::cout << 0;
  47.   else
  48.     std::cout << no;
  49.   return 0;
  50. }
复制代码



小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2014-2-15 20:31:31 | 显示全部楼层
我只是路过打酱油的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-8 11:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表