Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequence), or all pressed buttons return to the initial position. When all buttons are pressed into the lock at once, the lock opens.
Consider an example with three buttons. Let's say that the opening sequence is: {2, 3, 1}. If you first press buttons 1 or 3, the buttons unpress immediately. If you first press button 2, it stays pressed. If you press 1 after 2, all buttons unpress. If you press 3 after 2, buttons 3 and 2 stay pressed. As soon as you've got two pressed buttons, you only need to press button 1 to open the lock.
Manao doesn't know the opening sequence. But he is really smart and he is going to act in the optimal way. Calculate the number of times he's got to push a button in order to open the lock in the worst-case scenario.
A single line contains integer n (1 ≤ n ≤ 2000) — the number of buttons the lock has.
In a single line print the number of times Manao has to push a button in the worst-case scenario.
2
3
3
7
Consider the first test sample. Manao can fail his first push and push the wrong button. In this case he will already be able to guess the right one with his second push. And his third push will push the second right button. Thus, in the worst-case scenario he will only need 3 pushes.
解题思路:这题是一道数学题,给你n个按钮,必须要按照顺序按下去才会把一个锁打开,否则一步按错将会重置所有按钮,题目要求的就是在最坏情况下最多按多少次按钮就能把锁打开。考虑两个按钮的情况,如果顺序是先按2再按1,最坏的情况是先按1,发现重置了,再按2,可以,再按1,总共三步锁打开了。
下面拓展到n个情况,设每一轮我们都按下去一个按钮,假设我们都是在最后才按到正确的按钮上
第一轮,我们最多按n个按钮
第i轮(i<=n),我们已经按下去了i-1个按钮,剩下n-i+1个按钮要按,这一步我们需要找到第i个正确的按钮。依次判断剩下的按钮中某个按钮是不是正确,判断第一个按钮我们只需要1次,不过判断第2个按钮我们需要把之前i-1个按钮都按下再加上第2个按钮,剩下的依次类推,把上次按错按钮导致的重置步数加到确认下一个按钮的步数中,直到我们找到正确的按钮,这时需要按 (n-i)*i次。所以,第i轮总共需要按 1+(n-i)*i次按钮。
i从1到n,加起来就是题目中最多按按钮的次数。
#include <stdio.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <sstream>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <ctime>
using namespace std;
typedef long long LL;
int main() {
int t;
int n,m,k;
while(scanf("%d",&t)!=EOF){
int i = 0;
int sum = 0;
for(i = 1;i<=t;i++){
sum = sum + 1+(t-i)*i;
}
printf("%d\n",sum);
}
return 0;
}