scheme吧 关注:1,489贴子:963
  • 6回复贴,共1

我找到一个解决某问题的代码了

只看楼主收藏回复


@鸡蛋小哥
代码如下(等级不够不能上传啊..)
;r: result
;g: graph
;v: vertice
;p: path(length)
;plist: pair-list
;vp-plist: vertice-path-pair-list
;to-list: total-ordering-list
(define call/cc call-with-current-continuation)
(define topsort
(lambda (g)
(call/cc
(lambda (k)
(let ((t (top-vertice g)))
(if (not (= (length t) 1))
(k 'cyclic))
(let ((v (car t)))
(vp-plist->to-list (graph->vp-plist g v k))))))))
(define remove
(lambda (x ls)
(if (null? ls)
'()
(if (eqv? x (car ls))
(remove x (cdr ls))
(cons (car ls) (remove x (cdr ls)))))))
(define exist
(lambda (x ls)
(cond ((null? ls) #f)
((eqv? x (car ls)) #t)
(else (exist x (cdr ls))))))
(define sort
(lambda (ls)
(if (null? ls)
'()
(let ((t (apply max ls)))
(append (sort (remove t ls)) (list t))))))
(define pl-constructor
(lambda (keys default-value)
(map (lambda (x) (cons x default-value)) keys)))
(define pl-selector
(lambda (select-func ls)
(map (lambda (x) (select-func x)) ls)))
(define vertice
(lambda (g)
(pl-selector car g)))
(define top-vertice
(lambda (g)
(define v (vertice g))
(for-each
(lambda (x)
(for-each
(lambda (x)
(set! v (remove x v)))
(cdr x)))
g)
v))
(define graph->vp-list
(lambda (g v k)
(define result (pl-constructor (vertice g) 0))
(define update
(lambda (val key)
(let ((t (assq key result)))
(if (> val (cdr t))
(set-cdr! t val)))))
(let f ((cur v)
(path '()))
(if (exist cur path)
(k 'cyclic))
(update (length path) cur)
(for-each (lambda (x) (f x (cons cur path))) (cdr (assq cur g))))
result))
(define vp-plist->to-list
(lambda (pl)
(define temp (pl-constructor (map cdr pl) '()))
(define result '())
(for-each
(lambda (x)
(let ((t (assq (cdr x) temp)))
(set-cdr! t (append (cdr t) (list (car x))))))
pl)
(for-each (lambda (x) (set! result (append result (cdr (assq x temp))))) (sort (map car temp)))
result))
;(define g0 '((a b b e) (c) (b c) (d a b) (e d f) (f d)))
;(topsort g0)


1楼2014-06-15 23:29回复
    r5rs


    2楼2014-06-15 23:30
    回复
      还在吗


      IP属地:四川来自Android客户端3楼2016-07-24 19:18
      回复
        ...


        4楼2016-07-28 17:44
        回复
          楼主可以说明题目吗,好像挺有趣的


          5楼2016-07-28 17:44
          回复
            反正英文我是看不懂太懂的


            来自Android客户端6楼2016-10-01 19:37
            回复
              有向图找边?


              IP属地:立陶宛来自Android客户端7楼2019-12-15 10:07
              回复