INF = 1 << 20 def warshal(n,e) g = n.times.map { Array.new(n,INF) } n.times do |u| g[u][u] = 0 end e.each do |u,v| g[u][v] = g[v][u] = 1 end n.times do |i| n.times do |j| n.times do |k| if g[i][k] + g[k][j] < g[i][j] g[j][i] = g[i][j] = g[i][k] + g[k][j] end end end end g end def cover_all?(n, max_cost) s = (1 << n.size) dp = s.times.map { Array.new(n.size, INF) } q = [] n.each_with_index do |v, i| used = 1 << i cost = G[v][0] q.push([used, i, cost]) end until q.empty? used, pos, cost = q.shift u = n[pos] if cost < dp[used][pos] dp[used][pos] = cost n.each_with_index do |v,i| mask = 1 << i ncost = cost + G[v][u] if mask & used == 0 && ncost <= max_cost q.unshift([used | mask, i, ncost ]) end end end end dp[s - 1].min <= max_cost end n,m,k = gets.split.map(&:to_i) e = m.times.map { gets.split.map(&:to_i).map{|v| v - 1} } G = warshal(n,e) V = n.times.to_a.drop(1).reverse used = [] V.each do |v| if cover_all?(used.dup << v, k) used << v end end puts used.map{|v| (1 << v) - 1 }.inject(0, &:+)