用于计算物理实验的 C++ 代码
假设我们正在进行物理实验。我们给定 n 对值和阈值 k。将每对值中的第一个值添加到总值,将每对值中的第二个值也添加到另一个总值。现在,我们检查总值是否为最小值,或者 (k - 总值) 是否为最小值。我们对两个总值都执行此操作,然后将它们相加并打印输出。
因此,如果输入像 n = 4, k = 20, values = {{3, 5}, {4, 3}, {2, 1}, {4, 4}}, 则输出将为 14。
步骤
为了解决这个问题,我们将遵循以下步骤 -
a := 0, b = 0 for initialize i := 0, when i < n, update (increase i by 1), do: a := a + first value of values[i] b := b + second value of values[i] print(min((a, k - a) + minimum of b and k - b))
示例
让我们看看以下实现以加深理解 -
#include <bits/stdc++.h> using namespace std; #define N 100 void solve(int n, int k, vector<pair<int,int>> values) { int a = 0, b = 0; for(int i = 0; i < n; i++){ a += values[i].first; b += values[i].second; } cout<<min(a, k - a) + min(b, k - b); } int main() { int n = 4, k = 20; vector<pair<int,int>> values = {{3, 5}, {4, 3}, {2, 1}, {4, 4}}; solve(n, k, values); return 0; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输入
4, 20, {{3, 5}, {4, 3}, {2, 1}, {4, 4}}
输出
14
广告