Davor COCI 2018
当题目中有多组解,但要某值最大,该怎么办?
本文为博客园ShyButHandsome的原创作品,转载请注明出处
题目描述
After successfully conquering the South Pole, Davor is preparing for new challenges.
猛男\(Davor\)在从南极旅游回来之后,他又按耐不住想去看看别地的风景了。
Next up is the Arctic expedition to Siberia, Greenland and Norway.
琢磨了一宿,\(Davor\)第二天起床后就在它的旅行计划书上写下西伯利亚、格林兰、挪威的北极圈 2018.12.31出发
。
He begins his travels on \(31\ December\ 2018\), and needs to collect \(N\) kunas (Croatian currency) by then.
可是,这些地方有点远,而且。。。他没钱,咋办?借(募集)呗。
In order to do this,
为了借(pian)到这么多钱,
he has decided to put away \(X\ (X \leq 100)\) kunas every Monday to his travel fund,
他决定在每周周一,借\(X\ (X \leq 100)\)块钱,
\(X + K\) kunas every Tuesday,
然后第二天(也就是周二)增加挑战难度,多借\(K\)块钱(周二借\(X+K\)),
\(X + 2 * K\) every Wednesday,
周三又在周二基础上多借\(K (K > 0 )\)块(也就是\(X + 2 * K\)),
and so on until Sunday,
每个礼拜为一个周期,
when he will put away \(X + 6 * K\) kunas.
到周日当天就要借\(X + 6 * K\)块钱。
This way, he will collect money for \(52\) weeks, starting with \(1\ January\ 2018 (Monday)\) until \(30\ December\ 2018 (Sunday)\).
他总共可以攒\(52\)周的钱,从\(2018\)年\(1\)月\(1\)日(当日是周一),到\(2018\)年\(12\)月\(30\)日(当日是周日)。
If we know the amount of money \(N\),
如果我们知道他总共需要多少钱\(N\),
output the values \(X\) and \(K\) so that it is possible to collect the exact money amount in the given timespan.
输出他刚好攒够的时候\(X\)和\(K\)的值。
The solution will always exist, and if there are multiple, output the one with the greatest \(X\) and smallest \(K\) .
问题总有解,如果有多组解,输出\(X\)尽可能大,\(K\)尽可能小的那一组解。
分析
这题但从解决问题的角度来看的话,其实并不难。
只要模拟猛男\(Davor\)的每一天就可以了,
但问题是这样会的得出很多解,
所以关键就是,
要输出\(X\)尽可能大,\(K\)尽可能小的那一组解。
我当时琢磨了蛮久,
一开始想着把所有解储存在一个二维数组中,
然后再拿出来比较,
但那样的代码也太复杂了,
然后我转念一想,没必要对\(X\)和\(K\)严格配对好再比较,
这俩肯定是一一对应的,
我只要找到了\(K_{min}\)或者\(X_{max}\)我就得到了这组解,
把\(k\)从小到大枚举,\(x\)从大到小枚举,哪个首先成立,不就得出了这组解吗?
但这里其实题目有点没说清楚,
当\(X\)最大时\(K\)不一定最小,
也就是说,\(X_{max}\)的优先级更高,
找到满足条件的直接跳出就可以了。
代码实现
#include <bits/stdc++.h>
int main()
{
int n, x, k;
cin >> n;
// k是从小到大,开100准够
for (k = 1; k <= 100; ++k)
// x是从大到小
for (x = 100; x > 0; --x)
if ((7 * x + 21 * k) * 52 == n)
{
cout << x << endl << k << endl;
return 0;
}
}
如果您发现了我的错误,还望不吝赐教
我是ShyButHandsome,一个喜欢思考的小男孩,如果您喜欢这篇文章,不妨点点推荐?