CodeForces 1353 C. Board Moves 動態規劃

1. 題目描述

1.1. Limit

Time Limit: 1 second

Memory Limit: 256 megabytes

1.2. Problem Description

You are given a board of size n×nn \times n, where nn is odd (not divisible by 22). Initially, each cell of the board contains one figure.

In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i,j)(i, j) you can move the figure to cells:

  • (i1,j1)(i - 1, j - 1);

  • (i1,j)(i - 1, j);

  • (i1,j+1)(i - 1, j + 1);

  • (i,j1)(i, j - 1);

  • (i,j+1)(i, j + 1);

  • (i+1,j1)(i + 1, j - 1);

  • (i+1,j)(i + 1, j);

  • (i+1,j+1)(i + 1, j + 1);

Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.

Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. n21n^2-1 cells should contain 00 figures and one cell should contain n2n^2 figures).

You have to answer tt independent test cases.

1.3. Input

The first line of the input contains one integer tt (1t2001 \le t \le 200) — the number of test cases. Then tt test cases follow.

The only line of the test case contains one integer nn (1n<51051 \le n < 5 \cdot 10^5) — the size of the board. It is guaranteed that nn is odd (not divisible by 22).

It is guaranteed that the sum of nn over all test cases does not exceed 51055 \cdot 10^5 (n5105\sum n \le 5 \cdot 10^5).

1.4. Onput

For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.

1.5. Sample Input

3
1
5
499993

1.6. Sample Onput

0
40
41664916690999888

1.7. Source

CodeForces 1353 C. Board Moves


2. 解讀

通過觀察建立遞推方程,從矩陣中心向外,第 ii 層有 8i8i 個元素,需要移動 ii 次才能到達矩陣中心。

f(i)=f(i1)+8×(i1)2 f(i) = f(i-1) + 8 \times (i-1)^2

ii 換爲矩陣維度xxi=2x1i = 2x-1

f(2x1)=f(2(x1)1)+8×(2(x1)1)2 f(2x-1) = f(2(x-1)-1) + 8 \times (2(x-1)-1)^2


Table 1.樣例數據表 \text{Table 1.樣例數據表}

xx 2x12x-1 結果 差值
1 1 0
2 3 8 8
3 5 40 32
4 7 114 72
5 9 506 392
6 11 1164 648

3. 代碼

#include <algorithm>
#include <iostream>
#include <string.h>
const long long num = 5 * 1e5 + 1;
using namespace std;

long long list[num];

void calculate(long long n)
{
    list[1] = 0;
    // 遞推方程
    // 這裏的 i 一定要是 long long ,不然會溢出,猜測是(i - 1) * (i - 1)用了i的類型進行存儲
    for (long long i = 2; i < n; i++) {
        list[i] = list[i - 1] + 8 * (i - 1) * (i - 1);
    }
}

int main()
{
    // test case
    long long t;
    long long n;
    // 計算
    calculate((num + 1) / 2);
    // test case
    scanf("%lld", &t);
    // for each test case
    while (t--) {
        // 輸入
        scanf("%lld", &n);
        // 輸出
        printf("%lld\n", list[(n + 1) / 2]);
    }
}


聯繫郵箱:[email protected]

Github:https://github.com/CurrenWong

歡迎轉載/Star/Fork,有問題歡迎通過郵箱交流。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章