Swift 错误解决:将 ArraySlice 转换为 Array
import Foundation\nvar n: Int = 0\nvar ans: Int = 0\nfunc calculate(){\n let input = readLine()!.split(separator: " ").map{ Int($0)! }\n let w: [Int] = Array(input[0..<n])\n let a: [Int] = Array(input[n..<2*n])\n var dp: [Int] = w\n for i in 0..<n {\n for j in 0..<i {\n if (i - j) % a[j] == 0 {\n dp[i] = max(w[i] + dp[j], dp[i])\n }\n }\n ans = max(ans, dp[i])\n }\n print(ans)\n}\nfunc main(){\n n = Int(readLine()!)!\n calculate()\n}\nmain()\n\nThe error message indicates that there is an issue with the way the input array is being sliced.\n\nTo fix this, you can convert the ArraySlice to an Array by using the Array constructor.\n\nHere's the modified code:\n\nswift\nimport Foundation\n\nvar n: Int = 0\nvar ans: Int = 0\n\nfunc calculate() {\n let input = readLine()!.split(separator: " ").map{ Int($0)! }\n let w: [Int] = Array(input[0..<n])\n let a: [Int] = Array(input[n..<2*n])\n var dp: [Int] = w\n \n for i in 0..<n {\n for j in 0..<i {\n if (i - j) % a[j] == 0 {\n dp[i] = max(w[i] + dp[j], dp[i])\n }\n }\n ans = max(ans, dp[i])\n }\n \n print(ans)\n}\n\nfunc main() {\n n = Int(readLine()!)!\n calculate()\n}\n\nmain()\n\n\nThis should resolve the error and allow the code to run without issues.
原文地址: https://www.cveoy.top/t/topic/p207 著作权归作者所有。请勿转载和采集!