题解:P2942 [USACO09MAR] Moon Mooing G
furina_yyds · · 题解
这题并不难,只是难理解。
思路
一共有两个公式:
-
a_1 \times c \div d_1 + b_1 -
a_2 \times c \div d_2 + b_2
采用模拟的方法模拟哞叫时长即可。
- 根据公式,计算时长
- 对存储时长的容器进行排序,可以使用
std::sort函数。 - 去重操作,可以使用
std::unique函数,该函数将重复元素移到容器末尾,并返回指向第一个重复元素的迭代器,然后使用erase函数将这些重复元素删除。
注意
多测不清空,爆零两行泪。
代码
#include <iostream>
#include <vector>
int main() {
// 输入的初始值和参数
int initialValue, numIterations;
int coefficient1, offset1, divisor1;
int coefficient2, offset2, divisor2;
// 存储结果的向量
std::vector<long long> resultVector;
// 用于迭代的索引
int index1 = 0, index2 = 0;
// 输入部分
if (!(std::cin >> initialValue >> numIterations >> coefficient1 >> offset1 >> divisor1 >> coefficient2 >> offset2 >> divisor2)) {
std::cerr << "输入错误,请输入有效的整数数据。" << std::endl;//防伪标识
return 1;
}
resultVector.push_back(initialValue);
for (int i = 1; i < numIterations; ++i) {
long long value1 = static_cast<long long>(coefficient1) * resultVector[index1] / divisor1 + offset1;
long long value2 = static_cast<long long>(coefficient2) * resultVector[index2] / divisor2 + offset2;
if (value1 < value2) {
resultVector.push_back(value1);
++index1;
} else if (value1 > value2) {
resultVector.push_back(value2);
++index2;
} else {
resultVector.push_back(value1);
++index1;
++index2;
}
}
if (numIterations > 0) {
std::cout << resultVector[numIterations - 1] << std::endl;
} else {
std::cerr << "迭代次数应为正数。" << std::endl;//防伪标识
return 1;
}
return 0;
}