PAT A1103 Integer Factorization Go语言题解及注意事项

 

 

1103 Integer Factorization (30分)
 

The KP factorization of a positive integer N is to write N as the sum of the P-th power of K positive integers. You are supposed to write a program to find the KP factorization of N for any positive integers N, K and P.

Input Specification:

Each input file contains one test case which gives in a line the three positive integers N (≤), K (≤) and P (1). The numbers in a line are separated by a space.

Output Specification:

For each case, if the solution exists, output in the format:

N = n[1]^P + ... n[K]^P
 

where n[i] (i = 1, ..., K) is the i-th factor. All the factors must be printed in non-increasing order.

Note: the solution may not be unique. For example, the 5-2 factorization of 169 has 9 solutions, such as 1, or 1, or more. You must output the one with the maximum sum of the factors. If there is a tie, the largest factor sequence must be chosen -- sequence { , } is said to be larger than { , } if there exists 1 such that ai​​=bi​​ for i<L and aL​​>bL​​.

If there is no solution, simple output Impossible.

Sample Input 1:

169 5 2
 

Sample Output 1:

169 = 6^2 + 6^2 + 6^2 + 6^2 + 5^2
 

Sample Input 2:

169 167 3
 

Sample Output 2:

Impossible

思路:

暴力求解100%会超时,这里使用DFS进行求解,由题目要求,我们从最大的因子开始从大往小搜,在因子合相同时总是能先搜到最优解然后返回。

Solution(Golang):

package main

import (
	"fmt"
)

var (
	temp, fac []int
	ans       [100]int
	maxsum    int = 0
	n, p, k   int
	flag      = false
)

func pow(n, p int) int {
	a := n
	for i := 1; i < p; i++ {
		a *= n
	}
	return a
}

func init1() {
	fac = append(fac, 0)
	for i := 1; pow(i, p) <= n; i++ {
		fac = append(fac, pow(i, p))
	}
}

func dfs(index, num, value, sumfac int) {
	if num > k || value > n {
		return
	}
	if num == k {
		if value == n && sumfac > maxsum {
			flag = true
			maxsum = sumfac
			for i, v := range temp {
				ans[i] = v
			}

		}
		return
	}
	temp = append(temp, index)
	//fmt.Println(index)
	dfs(index, num+1, value+fac[index], sumfac+index)
	temp = temp[0 : len(temp)-1]
	if index > 1 {
		dfs(index-1, num, value, sumfac)
	}
}

func main() {
	fmt.Scan(&n, &k, &p)
	init1()

	dfs(len(fac)-1, 0, 0, 0)
	//fmt.Println(ans)
	if !flag {
		fmt.Println("Impossible")
	} else {
		fmt.Printf("%d = %d^%d", n, ans[0], p)
		for i := 1; i < k; i++ {
			fmt.Printf(" + %d^%d", ans[i], p)
		}
	}
	return
}

  

 

posted @ 2020-11-22 17:33  tao10203  阅读(131)  评论(0)    收藏  举报