Continuous Login ZOJ - 3768 (暴力)

Continuous Login

ZOJ - 3768

Pierre is recently obsessed with an online game. To encourage users to log in, this game will give users a continuous login reward. The mechanism of continuous login reward is as follows: If you have not logged in on a certain day, the reward of that day is 0, otherwise the reward is the previous day's plus 1.

On the other hand, Pierre is very fond of the number N. He wants to get exactly N points reward with the least possible interruption of continuous login.


Input

There are multiple test cases. The first line of input is an integer T indicates the number of test cases. For each test case:

There is one integer N (1 <= N <= 123456789).

Output

For each test case, output the days of continuous login, separated by a space.

This problem is special judged so any correct answer will be accepted.

Sample Input
4
20
19
6
9
Sample Output
4 4
3 4 2
3
2 3
Hint

20 = (1 + 2 + 3 + 4) + (1 + 2 + 3 + 4)

19 = (1 + 2 + 3) + (1 + 2 + 3 + 4) + (1 + 2)

6 = (1 + 2 + 3)

9 = (1 + 2) + (1 + 2 + 3)

Some problem has a simple, fast and correct solution.

题意:给你一个数n,要求这个数n只能由(1+2+3+……+k)这样的和组成,求组成n所需要的最小这样的数的个数,输出每个k

思路:这个题一直以为是什么高深的算法,1+2+……+15713就会大于123456789,所以一共就有15712个数,而且发现任意一个数n最多有三个这样的和组成,不会再多了,所以直接暴力一个组成的,两个组成的,三个组成的。

code:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int a[16000],b[1600000];
int cnt;
void init(){
    a[0] = 0;
    cnt = 0;
    for(int i = 1; i < 15713; i++){
        a[i] = a[i-1] + i;
    }
}

int main(){
    init();
    int t;
    int n,flag = 0;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        flag = 0;
        for(int i = 1; i <= 15712; i++){
            if(a[i] == n){//由一个构成
                flag = 1;
                printf("%d\n",i);
                break;
            }
        }
        if(flag) continue;
        for(int i = 1,j = 15712; i <= j;){
            if(a[i] + a[j] < n) i++;
            else if(a[i] + a[j] > n) j--;
            else{//由两个构成
                flag = 1;
                printf("%d %d\n",i,j);
                break;
            }
        }
        if(flag) continue;
        for(int i = 1; i <= 15712; i++){
            for(int j = 1,k = 15712; j <= k;){
                if(a[i] + a[j] + a[k] < n) j++;
                else if(a[i] + a[j] + a[k] > n) k--;
                else{//三个构成
                    flag = 1;
                    printf("%d %d %d\n",i,j,k);
                    break;
                }
            }
            if(flag) break;
        }
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/codeswarrior/article/details/80112894
ZOJ