AcWing 788. 逆序对的数量 Go
原题链接
简单
作者:
LaChimere
,
2021-03-17 17:14:26
,
所有人可见
,
阅读 337
package main
import "fmt"
func merge(a, b []int, cnt *int) []int {
res := make([]int, len(a)+len(b))
var i, j int
for i < len(a) && j < len(b) {
if a[i] <= b[j] {
res[i+j] = a[i]
i++
} else {
res[i+j] = b[j]
*cnt += len(a) - i
j++
}
}
for ; i < len(a); i++ {
res[i+j] = a[i]
}
for ; j < len(b); j++ {
res[i+j] = b[j]
}
return res
}
func MergeSort(a []int, cnt *int) []int {
if len(a) < 2 {
return a
}
mid := len(a)/2
left := MergeSort(a[:mid], cnt)
right := MergeSort(a[mid:], cnt)
return merge(left, right, cnt)
}
func main() {
var n int
fmt.Scanf("%d", &n)
nums := make([]int, n)
for i := 0; i < n; i++ {
fmt.Scanf("%d", &nums[i])
}
cnt := 0
MergeSort(nums, &cnt)
fmt.Println(cnt)
}