ZJU 3768 Continuous Login

數學找規律的題,先暴力打表觀察有什么規律,發現每個數只需要三個以內的三角形數的和就可以表示。
用限制步數的DFS搜索,到最后一步時加上二分優化。
打表是很重要的。

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#define OUT(x) cerr << #x << ": " << (x) << endl
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define SZ(x) ((int)x.size())
using namespace std;
typedef long long LL;

int points(int x) {
    return x * (x + 1) / 2;
}
vector<int> tri;

void output(const vector<int>& out) {
    for (int i = 0; i < SZ(out); ++i) {
        if (i) printf(" ");
        printf("%d", out[i]);
    }
    printf("\n");
}

bool dfs(int N, int cnt, int offset, vector<int>* ans) {
    if (cnt == 1) {
        int k = lower_bound(tri.begin() + offset, tri.end(), N) - tri.begin();
        if (k < SZ(tri) && tri[k] == N) {
            ans->push_back(k);
            output(*ans);
            ans->pop_back();
            return true;
        } else {
            return false;
        }
    }

    for (int i = offset; i >= 0; --i) {
        ans->push_back(i);
        if (dfs(N - tri[i], cnt - 1, i, ans)) {
            return true;
        }
        ans->pop_back();
    }
    return false;
}

int main() {
    tri.reserve((int)sqrt(2.0 * 123456789));
    for (int i = 0; points(i) <= 123456789; ++i) {
        tri.push_back(points(i));
    }

    int T, N;
    scanf("%d", &T);
    while (T--) {
        scanf("%d", &N);
        vector<int> ans;
        int offset = upper_bound(tri.begin(), tri.end(), N) - tri.begin() - 1;
        for (int cnt = 1; cnt <= 3; ++cnt) {
            if (dfs(N, cnt, offset, &ans)) break;
        }
    }
    return 0;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,766評論 0 33
  • (注:此文寫于2017年1月16日) 啊,折騰了自己好幾個月,終于,鼓起勇氣要開始自己的寫作之旅,加入“不寫就出局...
    峰回路又轉Andy閱讀 342評論 0 2
  • 01 今年的夏令營終于來了! 感恩這次的天廚,這幾天的素食能量實足,與大家分享一下健康素食! 上圖 02 小朋友就...
    袁袁_45fc閱讀 576評論 0 2
  • 很多年輕人結婚后卻不知道家庭的真正含義,家庭是什么? 家庭包括的太多,父母、兒女、親朋好友等等,都...
    冷水煮魚閱讀 329評論 0 0