Lily's Homework

  • + 0 comments

    This approach in Ruby:

    n = gets.to_i
    a = gets.strip.split.map &:to_i
    def find_swaps(a)
        map = a.each_with_index.map{|x,i| [x,i]}.to_h
        swaps = 0; sort = a.sort
        for i in 0...a.size do
            if sort[i] != a[i]
                swaps += 1
                map[a[i]] = map[sort[i]]
                a[map[sort[i]]], a[i] = a[i], sort[i] end end
        swaps end
    puts [find_swaps(Marshal.load(Marshal.dump(a))),find_swaps(a.reverse)].min