6.22华为OD机试真题 新系统 - 预测新能源发电量 (Java/Py/C/C++/Js/Go)
预测新能源发电量
2026 华为OD机试真题 6月22日华为OD上机新系统考试真题 100 分题型
点击查看华为 OD 机试真题完整目录:2026最新华为OD机试新系统卷 + 双机位C卷 真题题库目录|全覆盖题库 + 逐点算法考点详解
题目描述
某地面光伏电站按区域划分为多个子阵。每个子阵的发电能力有明确的约束:
- 发电能力上限(max_capacity)
- 发电能力下限(min_capacity)
- 基准发电量(base_generation)
系统需要根据这些约束,预测整个电站的发电量。预测策略是:
- 每个子阵有一个基准发电量
- 如果总预测发电量超过电站总容量,需要按比例缩减
- 如果总预测发电量低于总容量下限,需要按比例放大
- 最终预测发电量向上取整为整数
调整策略
缩减场景
当总发电量超过电站容量时,按各子阵的可用缩减空间比例分配缩减量
可用缩减空间 = base_generation − min_capacity;表示该子阵还能减少多少发电量而不低于下限
缩减量按此比例分配:缩减量i = 总缩减量 × (可用缩减空间i / 总可用缩减空间)
放大场景
当总发电量低于总下限时,按各子阵的可用放大空间比例分配增加量
可用放大空间 = max_capacity - base_generation;表示该子阵还能增加多少发电量而不超过上限
增加量按此比例分配:增加量i = 总增加量 × (可用放大空间i / 总可用放大空间)
输入描述
sub_arrays: 子阵列表,每个子阵是一个三元组[max_capacity, min_capacity, base_generation],均为整数
station_capacity: 电站总容量上限(整数)
输出描述
返回一维数组,每个元素是对应子阵的预测发电量(向上整数) 如果无法在约束范围内满足总容量要求,返回全 0 数组
特殊情况处理
- 如果所有子阵都达到下限,但仍超过电站容量:返回全 0 数组
- 如果所有子阵都达到上限,但仍低于总下限:返回全 0 数组
要求
最终预测发电量必须满足:min_capacity≤predicted_generation≤max_capacity
- 如果总预测发电量 > station_capacity,需要按比例缩减
- 如果总预测发电量 < 总下限(各子阵min_capacity之和),需要按比例放大
- 最终结果必须向上取整为整数(如使用math.ceil)
示例1
输入
[[1000, 800, 900],[1200, 900, 1100],[800, 600, 700]],2800
输出
[900,1100,700]
说明
示例2
输入
[[1000, 800, 800],[1200, 900, 900],[800, 600, 600]],2600
输出
[800,900,600]
说明
解题思路
核心思想
本题的核心是根据各子阵的发电能力约束(上限、下限、基准值),按比例调整预测发电量以满足电站总容量要求。
1. 情况判断
- 无需调整:总基准发电量在 [总下限, 电站容量] 范围内
- 需要缩减:总基准 > 电站容量,按可缩减空间比例分配缩减量
- 需要放大:总基准 < 总下限,按可放大空间比例分配增加量
2. 缩减策略
当总发电量超过电站容量时:
- 计算每个子阵的可缩减空间 = 基准值 - 下限
- 计算总缩减量 = 总基准 - 电站容量
- 每个子阵的缩减量 = 总缩减量 × (该子阵可缩减空间 / 总可缩减空间)
3. 放大策略
当总发电量低于总下限时:
- 计算每个子阵的可放大空间 = 上限 - 基准值
- 计算总增加量 = 总下限 - 总基准
- 每个子阵的增加量 = 总增加量 × (该子阵可放大空间 / 总可放大空间)
4. 特殊情况
- 如果所有子阵都达到下限但仍超过容量 → 返回全0
- 如果所有子阵都达到上限但仍低于下限 → 返回全0
- 最终结果向上取整
复杂度分析
- 时间复杂度:O(n),只需遍历子阵数组一次
- 空间复杂度:O(n),用于存储中间计算结果
Java
import java.util.*;
import java.util.stream.Collectors;
/**
* 预测新能源发电量解决方案
*
* 核心思路:
* 1. 提取各子阵的上限、下限、基准发电量
* 2. 根据总基准与电站容量的关系,判断是否需要调整
* 3. 如果需要缩减/放大,按各子阵的可调整空间比例分配调整量
* 4. 最终结果向上取整
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取完整输入(单行格式:[[...]],capacity)
String inputLine = scanner.nextLine().trim();
// 找到最后一个逗号的位置来分割数组和容量
int lastComma = inputLine.lastIndexOf(',');
String subArraysStr = inputLine.substring(0, lastComma).trim();
int stationCapacity = Integer.parseInt(inputLine.substring(lastComma + 1).trim());
// 解析子阵数组
List<List<Integer>> subArrays = parseSubArrays(subArraysStr);
// 调用解决方案
List<Integer> result = predictGeneration(subArrays, stationCapacity);
// 输出结果(格式:[x1,x2,x3])
System.out.print("[");
for (int i = 0; i < result.size(); i++) {
if (i > 0) System.out.print(",");
System.out.print(result.get(i));
}
System.out.println("]");
}
/**
* 预测新能源发电量
*
* @param subArrays 子阵列表,每项为[上限, 下限, 基准发电量]
* @param stationCapacity 电站总容量上限
* @return 每个子阵的预测发电量(向上取整)
*/
public static List<Integer> predictGeneration(
List<List<Integer>> subArrays, int stationCapacity) {
int n = subArrays.size();
if (n == 0) {
return new ArrayList<>();
}
// 提取各子阵的参数
int[] maxCapacities = new int[n];
int[] minCapacities = new int[n];
int[] baseGenerations = new int[n];
for (int i = 0; i < n; i++) {
maxCapacities[i] = subArrays.get(i).get(0);
minCapacities[i] = subArrays.get(i).get(1);
baseGenerations[i] = subArrays.get(i).get(2);
}
// 计算总量
int totalBase = Arrays.stream(baseGenerations).sum();
int totalMin = Arrays.stream(minCapacities).sum();
// 初始化预测发电量(使用double便于计算)
double[] predicted = new double[n];
for (int i = 0; i < n; i++) {
predicted[i] = baseGenerations[i];
}
// 场景1:总基准超过电站容量,需要按比例缩减
if (totalBase > stationCapacity) {
int reductionNeeded = totalBase - stationCapacity;
// 各子阵的可用缩减空间
int[] reducibleSpaces = new int[n];
int totalReducible = 0;
for (int i = 0; i < n; i++) {
reducibleSpaces[i] = baseGenerations[i] - minCapacities[i];
totalReducible += reducibleSpaces[i];
}
// 无法缩减,返回全0
if (totalReducible == 0) {
return Collections.nCopies(n, 0);
}
// 按比例分配缩减量
for (int i = 0; i < n; i++) {
double ratio = (double) reducibleSpaces[i] / totalReducible;
predicted[i] = baseGenerations[i] - reductionNeeded * ratio;
}
}
// 场景2:总基准低于各子阵下限之和,需要按比例放大
else if (totalBase < totalMin) {
int increaseNeeded = totalMin - totalBase;
// 各子阵的可用放大空间
int[] expandableSpaces = new int[n];
int totalExpandable = 0;
for (int i = 0; i < n; i++) {
expandableSpaces[i] = maxCapacities[i] - baseGenerations[i];
totalExpandable += expandableSpaces[i];
}
// 无法放大,返回全0
if (totalExpandable == 0) {
return Collections.nCopies(n, 0);
}
// 按比例分配增加量
for (int i = 0; i < n; i++) {
double ratio = (double) expandableSpaces[i] / totalExpandable;
predicted[i] = baseGenerations[i] + increaseNeeded * ratio;
}
}
// 向上取整,并减去微小量避免浮点边界误判
List<Integer> result = new ArrayList<>();
for (double v : predicted) {
result.add((int) Math.ceil(v - 1e-12));
}
return result;
}
/**
* 解析子阵数组字符串
*/
private static List<List<Integer>> parseSubArrays(String line) {
List<List<Integer>> result = new ArrayList<>();
// 移除方括号
String content = line.substring(1, line.length() - 1);
if (content.trim().isEmpty()) {
return result;
}
// 分割各子阵
int depth = 0;
int start = 0;
for (int i = 0; i < content.length(); i++) {
if (content.charAt(i) == '[') depth++;
else if (content.charAt(i) == ']') depth--;
else if (content.charAt(i) == ',' && depth == 0) {
result.add(parseSubArray(content.substring(start, i).trim()));
start = i + 1;
}
}
// 最后一个子阵
result.add(parseSubArray(content.substring(start).trim()));
return result;
}
/**
* 解析单个子阵
*/
private static List<Integer> parseSubArray(String s) {
List<Integer> result = new ArrayList<>();
String content = s.substring(1, s.length() - 1);
String[] parts = content.split(",");
for (String part : parts) {
result.add(Integer.parseInt(part.trim()));
}
return result;
}
}
Python
import math
from typing import List
def predict_generation(sub_arrays: List[List[int]], station_capacity: int) -> List[int]:
"""
预测新能源发电量
Args:
sub_arrays: 子阵列表,每项为[上限, 下限, 基准发电量]
station_capacity: 电站总容量上限
Returns:
每个子阵的预测发电量(向上取整)
"""
n = len(sub_arrays)
if n == 0:
return []
# 提取各子阵的参数
max_capacities = [row[0] for row in sub_arrays] # 上限
min_capacities = [row[1] for row in sub_arrays] # 下限
base_generations = [row[2] for row in sub_arrays] # 基准发电量
# 计算总量
total_base = sum(base_generations)
total_min = sum(min_capacities)
# 初始化预测发电量(使用float便于计算)
predicted = [float(x) for x in base_generations]
# 场景1:总基准超过电站容量,需要按比例缩减
if total_base > station_capacity:
# 需要缩减的量
reduction_needed = total_base - station_capacity
# 各子阵的可用缩减空间
reducible_spaces = [base_generations[i] - min_capacities[i] for i in range(n)]
total_reducible = sum(reducible_spaces)
# 无法缩减,返回全0
if total_reducible == 0:
return [0] * n
# 按比例分配缩减量
for i in range(n):
ratio = reducible_spaces[i] / total_reducible
predicted[i] = base_generations[i] - reduction_needed * ratio
# 场景2:总基准低于各子阵下限之和,需要按比例放大
elif total_base < total_min:
# 需要增加的量
increase_needed = total_min - total_base
# 各子阵的可用放大空间
expandable_spaces = [max_capacities[i] - base_generations[i] for i in range(n)]
total_expandable = sum(expandable_spaces)
# 无法放大,返回全0
if total_expandable == 0:
return [0] * n
# 按比例分配增加量
for i in range(n):
ratio = expandable_spaces[i] / total_expandable
predicted[i] = base_generations[i] + increase_needed * ratio
# 向上取整,并减去微小量避免浮点边界误判
return [math.ceil(v - 1e-12) for v in predicted]
def main():
"""主函数:处理输入输出"""
import sys
import ast
# 读取完整输入(单行格式:[[...]],capacity)
input_line = sys.stdin.read().strip()
# 找到最后一个逗号的位置来分割数组和容量
last_comma = input_line.rfind(',')
sub_arrays_str = input_line[:last_comma].strip()
station_capacity = int(input_line[last_comma + 1:].strip())
# 解析子阵数组
sub_arrays = ast.literal_eval(sub_arrays_str)
# 调用解决方案
result = predict_generation(sub_arrays, station_capacity)
# 输出结果(格式:[x1,x2,x3])
print("[" + ",".join(str(x) for x in result) + "]")
if __name__ == "__main__":
main()
JavaScript
/**
* 预测新能源发电量解决方案
*
* 核心思路:
* 1. 提取各子阵的上限、下限、基准发电量
* 2. 根据总基准与电站容量的关系,判断是否需要调整
* 3. 如果需要缩减/放大,按各子阵的可调整空间比例分配调整量
* 4. 最终结果向上取整
*/
/**
* 向上取整(处理浮点精度问题)
*/
function ceilMinusEps(num) {
return Math.ceil(num - 1e-12);
}
/**
* 预测新能源发电量
*
* @param {number[][]} subArrays - 子阵列表,每项为[上限, 下限, 基准发电量]
* @param {number} stationCapacity - 电站总容量上限
* @returns {number[]} 每个子阵的预测发电量(向上取整)
*/
function predictGeneration(subArrays, stationCapacity) {
const n = subArrays.length;
if (n === 0) {
return [];
}
// 提取各子阵的参数
const maxCapacities = subArrays.map(row => row[0]);
const minCapacities = subArrays.map(row => row[1]);
const baseGenerations = subArrays.map(row => row[2]);
// 计算总量
const totalBase = baseGenerations.reduce((a, b) => a + b, 0);
const totalMin = minCapacities.reduce((a, b) => a + b, 0);
// 初始化预测发电量
const predicted = baseGenerations.map(x => x);
// 场景1:总基准超过电站容量,需要按比例缩减
if (totalBase > stationCapacity) {
const reductionNeeded = totalBase - stationCapacity;
// 各子阵的可用缩减空间
const reducibleSpaces = [];
let totalReducible = 0;
for (let i = 0; i < n; i++) {
const space = baseGenerations[i] - minCapacities[i];
reducibleSpaces.push(space);
totalReducible += space;
}
// 无法缩减,返回全0
if (totalReducible === 0) {
return new Array(n).fill(0);
}
// 按比例分配缩减量
for (let i = 0; i < n; i++) {
const ratio = reducibleSpaces[i] / totalReducible;
predicted[i] = baseGenerations[i] - reductionNeeded * ratio;
}
}
// 场景2:总基准低于各子阵下限之和,需要按比例放大
else if (totalBase < totalMin) {
const increaseNeeded = totalMin - totalBase;
// 各子阵的可用放大空间
const expandableSpaces = [];
let totalExpandable = 0;
for (let i = 0; i < n; i++) {
const space = maxCapacities[i] - baseGenerations[i];
expandableSpaces.push(space);
totalExpandable += space;
}
// 无法放大,返回全0
if (totalExpandable === 0) {
return new Array(n).fill(0);
}
// 按比例分配增加量
for (let i = 0; i < n; i++) {
const ratio = expandableSpaces[i] / totalExpandable;
predicted[i] = baseGenerations[i] + increaseNeeded * ratio;
}
}
// 向上取整
return predicted.map(v => ceilMinusEps(v));
}
// 主函数
function main() {
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const lines = [];
rl.on('line', (line) => {
lines.push(line);
});
rl.on('close', () => {
// 读取完整输入(单行格式:[[...]],capacity)
const inputLine = lines.join('').trim();
// 找到最后一个逗号的位置来分割数组和容量
const lastComma = inputLine.lastIndexOf(',');
const subArraysStr = inputLine.substring(0, lastComma).trim();
const stationCapacity = parseInt(inputLine.substring(lastComma + 1).trim(), 10);
// 解析输入
const subArrays = JSON.parse(subArraysStr);
// 调用解决方案
const result = predictGeneration(subArrays, stationCapacity);
// 输出结果(格式:[x1,x2,x3])
console.log("[" + result.join(",") + "]");
});
}
main();
C++
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <sstream>
#include <algorithm>
using namespace std;
/**
* 预测新能源发电量解决方案
*
* 核心思路:
* 1. 提取各子阵的上限、下限、基准发电量
* 2. 根据总基准与电站容量的关系,判断是否需要调整
* 3. 如果需要缩减/放大,按各子阵的可调整空间比例分配调整量
* 4. 最终结果向上取整
*/
/**
* 向上取整(处理浮点精度问题)
*/
int ceilMinusEps(double num) {
return (int)ceil(num - 1e-12);
}
/**
* 解析子阵数组字符串
*/
vector<vector<int>> parseSubArrays(const string& line) {
vector<vector<int>> result;
string content = line.substr(1, line.length() - 2); // 移除外层方括号
if (content.empty()) {
return result;
}
int depth = 0;
size_t start = 0;
for (size_t i = 0; i < content.length(); i++) {
char c = content[i];
if (c == '[') depth++;
else if (c == ']') depth--;
else if (c == ',' && depth == 0) {
result.push_back(parseSubArray(content.substr(start, i - start)));
start = i + 1;
}
}
// 最后一个子阵
result.push_back(parseSubArray(content.substr(start)));
return result;
}
/**
* 解析单个子阵
*/
vector<int> parseSubArray(const string& s) {
vector<int> result;
string content = s.substr(1, s.length() - 2); // 移除方括号
stringstream ss(content);
string item;
while (getline(ss, item, ',')) {
result.push_back(stoi(item));
}
return result;
}
/**
* 预测新能源发电量
*/
vector<int> predictGeneration(const vector<vector<int>>& subArrays, int stationCapacity) {
int n = subArrays.size();
if (n == 0) {
return {};
}
// 提取各子阵的参数
vector<int> maxCapacities(n), minCapacities(n), baseGenerations(n);
for (int i = 0; i < n; i++) {
maxCapacities[i] = subArrays[i][0];
minCapacities[i] = subArrays[i][1];
baseGenerations[i] = subArrays[i][2];
}
// 计算总量
int totalBase = 0, totalMin = 0;
for (int i = 0; i < n; i++) {
totalBase += baseGenerations[i];
totalMin += minCapacities[i];
}
// 初始化预测发电量
vector<double> predicted(n);
for (int i = 0; i < n; i++) {
predicted[i] = baseGenerations[i];
}
// 场景1:总基准超过电站容量,需要按比例缩减
if (totalBase > stationCapacity) {
int reductionNeeded = totalBase - stationCapacity;
// 各子阵的可用缩减空间
vector<int> reducibleSpaces(n);
int totalReducible = 0;
for (int i = 0; i < n; i++) {
reducibleSpaces[i] = baseGenerations[i] - minCapacities[i];
totalReducible += reducibleSpaces[i];
}
// 无法缩减,返回全0
if (totalReducible == 0) {
return vector<int>(n, 0);
}
// 按比例分配缩减量
for (int i = 0; i < n; i++) {
double ratio = (double)reducibleSpaces[i] / totalReducible;
predicted[i] = baseGenerations[i] - reductionNeeded * ratio;
}
}
// 场景2:总基准低于各子阵下限之和,需要按比例放大
else if (totalBase < totalMin) {
int increaseNeeded = totalMin - totalBase;
// 各子阵的可用放大空间
vector<int> expandableSpaces(n);
int totalExpandable = 0;
for (int i = 0; i < n; i++) {
expandableSpaces[i] = maxCapacities[i] - baseGenerations[i];
totalExpandable += expandableSpaces[i];
}
// 无法放大,返回全0
if (totalExpandable == 0) {
return vector<int>(n, 0);
}
// 按比例分配增加量
for (int i = 0; i < n; i++) {
double ratio = (double)expandableSpaces[i] / totalExpandable;
predicted[i] = baseGenerations[i] + increaseNeeded * ratio;
}
}
// 向上取整
vector<int> result(n);
for (int i = 0; i < n; i++) {
result[i] = ceilMinusEps(predicted[i]);
}
return result;
}
int main() {
string line;
string inputLine;
// 读取完整输入(单行格式:[[...]],capacity)
while (getline(cin, line)) {
inputLine += line;
}
// 找到最后一个逗号的位置来分割数组和容量
size_t lastComma = inputLine.rfind(',');
string subArraysStr = inputLine.substr(0, lastComma);
int stationCapacity = stoi(inputLine.substr(lastComma + 1));
// 解析子阵数组
vector<vector<int>> subArrays = parseSubArrays(subArraysStr);
// 调用解决方案
vector<int> result = predictGeneration(subArrays, stationCapacity);
// 输出结果(格式:[x1,x2,x3])
cout << "[";
for (size_t i = 0; i < result.size(); i++) {
if (i > 0) cout << ",";
cout << result[i];
}
cout << "]" << endl;
return 0;
}
Go
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
/**
* 预测新能源发电量解决方案
*
* 核心思路:
* 1. 提取各子阵的上限、下限、基准发电量
* 2. 根据总基准与电站容量的关系,判断是否需要调整
* 3. 如果需要缩减/放大,按各子阵的可调整空间比例分配调整量
* 4. 最终结果向上取整
*/
/**
* 向上取整(处理浮点精度问题)
*/
func ceilMinusEps(num float64) int {
return int(num + 1 - 1e-12)
}
/**
* 解析子阵数组字符串
*/
func parseSubArrays(line string) [][]int {
result := [][]int{}
// 移除首尾方括号
content := strings.TrimSpace(line)
if len(content) < 2 {
return result
}
content = content[1 : len(content)-1]
if strings.TrimSpace(content) == "" {
return result
}
// 手动分割子阵
var subArrays []string
var current strings.Builder
depth := 0
for _, ch := range content {
switch ch {
case '[':
depth++
current.WriteRune(ch)
case ']':
depth--
current.WriteRune(ch)
if depth == 0 {
subArrays = append(subArrays, current.String())
current.Reset()
}
case ',':
if depth == 0 {
continue
}
current.WriteRune(ch)
default:
current.WriteRune(ch)
}
}
// 解析每个子阵
for _, s := range subArrays {
s = strings.TrimSpace(s)
if len(s) < 2 {
continue
}
inner := s[1 : len(s)-1]
nums := strings.Split(inner, ",")
var row []int
for _, n := range nums {
n = strings.TrimSpace(n)
if v, err := strconv.Atoi(n); err == nil {
row = append(row, v)
}
}
result = append(result, row)
}
return result
}
/**
* 预测新能源发电量
*/
func predictGeneration(subArrays [][]int, stationCapacity int) []int {
n := len(subArrays)
if n == 0 {
return []int{}
}
// 提取各子阵的参数
maxCapacities := make([]int, n)
minCapacities := make([]int, n)
baseGenerations := make([]int, n)
for i := 0; i < n; i++ {
maxCapacities[i] = subArrays[i][0]
minCapacities[i] = subArrays[i][1]
baseGenerations[i] = subArrays[i][2]
}
// 计算总量
totalBase := 0
totalMin := 0
for i := 0; i < n; i++ {
totalBase += baseGenerations[i]
totalMin += minCapacities[i]
}
// 初始化预测发电量
predicted := make([]float64, n)
for i := 0; i < n; i++ {
predicted[i] = float64(baseGenerations[i])
}
// 场景1:总基准超过电站容量,需要按比例缩减
if totalBase > stationCapacity {
reductionNeeded := totalBase - stationCapacity
// 各子阵的可用缩减空间
reducibleSpaces := make([]int, n)
totalReducible := 0
for i := 0; i < n; i++ {
reducibleSpaces[i] = baseGenerations[i] - minCapacities[i]
totalReducible += reducibleSpaces[i]
}
// 无法缩减,返回全0
if totalReducible == 0 {
result := make([]int, n)
return result
}
// 按比例分配缩减量
for i := 0; i < n; i++ {
ratio := float64(reducibleSpaces[i]) / float64(totalReducible)
predicted[i] = float64(baseGenerations[i]) - float64(reductionNeeded)*ratio
}
} else if totalBase < totalMin {
increaseNeeded := totalMin - totalBase
// 各子阵的可用放大空间
expandableSpaces := make([]int, n)
totalExpandable := 0
for i := 0; i < n; i++ {
expandableSpaces[i] = maxCapacities[i] - baseGenerations[i]
totalExpandable += expandableSpaces[i]
}
// 无法放大,返回全0
if totalExpandable == 0 {
result := make([]int, n)
return result
}
// 按比例分配增加量
for i := 0; i < n; i++ {
ratio := float64(expandableSpaces[i]) / float64(totalExpandable)
predicted[i] = float64(baseGenerations[i]) + float64(increaseNeeded)*ratio
}
}
// 向上取整
result := make([]int, n)
for i := 0; i < n; i++ {
result[i] = ceilMinusEps(predicted[i])
}
return result
}
func isDigit(r rune) bool {
return r >= '0' && r <= '9'
}
func main() {
reader := bufio.NewReader(os.Stdin)
// 读取完整输入(单行格式:[[...]],capacity)
var inputLine string
for {
line, err := reader.ReadString('\n')
inputLine += line
if err != nil {
break
}
}
inputLine = strings.TrimSpace(inputLine)
// 找到最后一个逗号的位置来分割数组和容量
lastComma := strings.LastIndex(inputLine, ",")
subArraysStr := strings.TrimSpace(inputLine[:lastComma])
stationCapacity, _ := strconv.Atoi(strings.TrimSpace(inputLine[lastComma+1:]))
// 解析子阵数组
subArrays := parseSubArrays(subArraysStr)
// 调用解决方案
result := predictGeneration(subArrays, stationCapacity)
// 输出结果(格式:[x1,x2,x3])
fmt.Print("[")
for i, v := range result {
if i > 0 {
fmt.Print(",")
}
fmt.Print(v)
}
fmt.Println("]")
}
C语言
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
/**
* 预测新能源发电量解决方案
*
* 核心思路:
* 1. 提取各子阵的上限、下限、基准发电量
* 2. 根据总基准与电站容量的关系,判断是否需要调整
* 3. 如果需要缩减/放大,按各子阵的可调整空间比例分配调整量
* 4. 最终结果向上取整
*/
#define MAX_ARRAY_SIZE 1000
#define MAX_TOKEN_SIZE 50
/**
* 向上取整(处理浮点精度问题)
*/
int ceilMinusEps(double num) {
return (int)ceil(num - 1e-12);
}
/**
* 去除字符串首尾空格
*/
void trim(char *dest, const char *src) {
while (isspace((unsigned char)*src)) src++;
int len = strlen(src);
while (len > 0 && isspace((unsigned char)src[len - 1])) len--;
strncpy(dest, src, len);
dest[len] = '\0';
}
/**
* 解析子阵数组
*/
int parseSubArrays(const char *line, int maxCapacities[], int minCapacities[], int baseGenerations[], int *n) {
// 分配临时内存
char *content = (char *)malloc(strlen(line) + 1);
trim(content, line);
// 移除首尾方括号
if (content[0] == '[') memmove(content, content + 1, strlen(content));
int len = strlen(content);
if (len > 0 && content[len - 1] == ']') content[len - 1] = '\0';
*n = 0;
int depth = 0;
int start = 0;
for (int i = 0; i <= strlen(content); i++) {
if (content[i] == '[') depth++;
else if (content[i] == ']') depth--;
else if ((content[i] == ',' && depth == 0) || content[i] == '\0') {
// 提取子阵
char subArray[256];
int subLen = i - start;
strncpy(subArray, content + start, subLen);
subArray[subLen] = '\0';
// 解析子阵 [max,min,base]
char *token = strtok(subArray, "[],");
int values[3];
int idx = 0;
while (token != NULL && idx < 3) {
values[idx++] = atoi(token);
token = strtok(NULL, "[],");
}
if (idx == 3) {
maxCapacities[*n] = values[0];
minCapacities[*n] = values[1];
baseGenerations[*n] = values[2];
(*n)++;
}
start = i + 1;
}
}
free(content);
return 0;
}
/**
* 预测新能源发电量
*/
void predictGeneration(int n, int maxCapacities[], int minCapacities[], int baseGenerations[], int stationCapacity, int result[]) {
if (n == 0) {
return;
}
// 计算总量
int totalBase = 0;
int totalMin = 0;
for (int i = 0; i < n; i++) {
totalBase += baseGenerations[i];
totalMin += minCapacities[i];
}
// 初始化预测发电量
double predicted[MAX_ARRAY_SIZE];
for (int i = 0; i < n; i++) {
predicted[i] = baseGenerations[i];
}
// 场景1:总基准超过电站容量,需要按比例缩减
if (totalBase > stationCapacity) {
int reductionNeeded = totalBase - stationCapacity;
// 各子阵的可用缩减空间
int reducibleSpaces[MAX_ARRAY_SIZE];
int totalReducible = 0;
for (int i = 0; i < n; i++) {
reducibleSpaces[i] = baseGenerations[i] - minCapacities[i];
totalReducible += reducibleSpaces[i];
}
// 无法缩减,返回全0
if (totalReducible == 0) {
for (int i = 0; i < n; i++) result[i] = 0;
return;
}
// 按比例分配缩减量
for (int i = 0; i < n; i++) {
double ratio = (double)reducibleSpaces[i] / totalReducible;
predicted[i] = baseGenerations[i] - reductionNeeded * ratio;
}
}
// 场景2:总基准低于各子阵下限之和,需要按比例放大
else if (totalBase < totalMin) {
int increaseNeeded = totalMin - totalBase;
// 各子阵的可用放大空间
int expandableSpaces[MAX_ARRAY_SIZE];
int totalExpandable = 0;
for (int i = 0; i < n; i++) {
expandableSpaces[i] = maxCapacities[i] - baseGenerations[i];
totalExpandable += expandableSpaces[i];
}
// 无法放大,返回全0
if (totalExpandable == 0) {
for (int i = 0; i < n; i++) result[i] = 0;
return;
}
// 按比例分配增加量
for (int i = 0; i < n; i++) {
double ratio = (double)expandableSpaces[i] / totalExpandable;
predicted[i] = baseGenerations[i] + increaseNeeded * ratio;
}
}
// 向上取整
for (int i = 0; i < n; i++) {
result[i] = ceilMinusEps(predicted[i]);
}
}
int main() {
char line[8192];
int maxCapacities[MAX_ARRAY_SIZE];
int minCapacities[MAX_ARRAY_SIZE];
int baseGenerations[MAX_ARRAY_SIZE];
int n = 0;
int stationCapacity;
// 读取完整输入(单行格式:[[...]],capacity)
char inputLine[8192] = "";
while (fgets(line, sizeof(line), stdin) != NULL) {
strcat(inputLine, line);
}
trim(inputLine, inputLine);
// 找到最后一个逗号的位置来分割数组和容量
char *lastComma = strrchr(inputLine, ',');
if (lastComma != NULL) {
*lastComma = '\0';
trim(inputLine, inputLine);
stationCapacity = atoi(lastComma + 1);
}
// 解析子阵数组
parseSubArrays(inputLine, maxCapacities, minCapacities, baseGenerations, &n);
// 调用解决方案
int result[MAX_ARRAY_SIZE];
predictGeneration(n, maxCapacities, minCapacities, baseGenerations, stationCapacity, result);
// 输出结果(格式:[x1,x2,x3])
printf("[");
for (int i = 0; i < n; i++) {
if (i > 0) printf(",");
printf("%d", result[i]);
}
printf("]\n");
return 0;
}
完整用例
用例1
[[1000, 800, 900],[1200, 900, 1100],[800, 600, 700]],2800
用例2
[[1000, 800, 800],[1200, 900, 900],[800, 600, 600]],2600
用例3
[[1000, 800, 900],[1000, 800, 900]],1500
用例4
[[1000, 800, 800],[1000, 800, 800]],1700
用例5
[[1000, 900, 900],[1000, 900, 900]],1700
用例6
[[1000, 800, 1000],[1000, 800, 1000]],1500
用例7
[[1000, 500, 600]],800
用例8
[[500, 400, 450],[600, 500, 550],[700, 600, 650]],1500
用例9
[[100, 80, 90],[200, 150, 180]],270
用例10
[[100, 80, 80],[200, 150, 150]],230
文章目录

更多推荐
所有评论(0)