[Programming questions] stone impact deft 20 Golang

[Programming problem] stone impact
we may consider the following procedure:
the stone divided into two piles, one pile stone taken from m A, B taken stack n, may assume that m> = n.
After the collision debris is mn, A heap should be placed.
Before and after the collision, you'll find two stacks of poor quality has not changed. Repeat until the time of the collision and go left a pile, you'll find the rest of the difference is the quality of the piles. Really very clever, so in order to make the final quality of the remaining minimum, we should let the quality of piles of stones as close as possible, that is, as far as possible the average.
In addition, where the inner layer for very clever. I started to write that i ++, this will lead to the reuse v. For example, v is a stone of 20, 40, 60 ... it will be marked as true. Sliding scale circulation can avoid this problem.

package main

import (
	"fmt"
)

func main() {
	var n, tmp, sum, max int
	var w []int
	fmt.Scan(&n)
	for i := 0; i < n; i++ {
		fmt.Scan(&tmp)
		sum += tmp
		w = append(w, tmp)
	}
	flag := make([]bool, sum/2+1)
	flag[0] = true
	for _, v := range w {
		for i := sum / 2; i >= v; i-- {
			flag[i] = flag[i] || flag[i-v]
		}
	}
	for i := sum / 2; i >= 0; i-- {
		if flag[i] {
			fmt.Print(sum - 2*i)
			break
		}
	}
}
Published 38 original articles · won praise 0 · Views 1010

Guess you like

Origin blog.csdn.net/Cyan1956/article/details/105332999