免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4619 | 回复: 2
打印 上一主题 下一主题

请数学高手帮忙证明算法。 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-08-30 10:00 |只看该作者 |倒序浏览
前几天看到hdu 1195:
Now an emergent task for you is to open a password lock. The password is consisted of four digits. Each digit is numbered from 1 to 9.
Each time, you can add or minus 1 to any digit. When add 1 to '9', the digit will change to be '1' and when minus 1 to '1', the digit will change to be '9'. You can also exchange the digit with its neighbor. Each action will take one step.

Now your task is to use minimal steps to open the lock.

Note: The leftmost digit is not the neighbor of the rightmost digit.
我用如下代码解,其中用到了两个假设:
1. 对于给定操作步骤,操作顺序可以打乱。(将各位编号,交换同时交换编号,增减操作绑定编号)
2. 对于可通过纯交换实现的变化,则最少交换步骤等同于将源组合冒泡排序至目标组合。

calculate函数求解,参数为 源状态 终状态,结果为 (最少步数, _)
  1. import Data.Maybe
  2. import Data.List

  3. steps4Exchange :: [ Int ] -> Int
  4. steps4Exchange dst =
  5.   snd $ iterate swapPass (dst, 0) !! (length dst - 1)
  6.   where swapPass ([ x ], i) = ([ x ], i)
  7.         swapPass (x : y : zs, i)
  8.           | x > y =
  9.             let (xs, i') = swapPass (x : zs, i + 1) in
  10.             (y : xs, i')
  11.           | otherwise =
  12.               let (xs, i') = swapPass (y : zs, i) in
  13.               (x : xs, i')

  14. steps4Move :: [ Int ] -> [ Int ] -> Int
  15. steps4Move src dst =
  16.   sum $ map (\(s, i) ->
  17.               let d = dst !! i in
  18.               min (abs (d - s)) (9 + s - d)
  19.            ) $ zip src [ 0 .. ]

  20. calculate :: [ Int ] -> [ Int ] -> (Int, [ Int ])
  21. calculate src dst =
  22.   let src' = zip src [ 0 .. ] in
  23.   foldl1 (\(a, a') (b, b') ->
  24.            if a > b then
  25.              (b, b')
  26.            else
  27.              (a, a')
  28.         ) $ map (\mid' ->
  29.                    let mid = fst $ unzip mid' in
  30.                    (steps4Exchange (snd $ unzip mid') + steps4Move mid dst, mid)
  31.                 ) $ permutations src'
复制代码

论坛徽章:
0
2 [报告]
发表于 2010-08-31 20:50 |只看该作者
这个貌似是BFS获取最小步数吧,你想证明什么{:3_196:}

论坛徽章:
0
3 [报告]
发表于 2010-09-02 16:18 |只看该作者
这个貌似是BFS获取最小步数吧,你想证明什么
daybreakcx 发表于 2010-08-31 20:50



    算是个bfs的应用优化问题吧。目的是减少需要遍历的元素。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP