题目链接

题目链接

题目大意

给你一个2023行的杨辉三角,然后按照从左到右从上到下的顺序标号,每个序号的方块值等于自己序号的平方,问你打掉某个序号的方块,所有掉落方块的值的和是多少?打掉一个方块,该方块连接的也会掉(上一层)打掉9会掉5,6。

题解

大概就是2023*2023/2的时间复杂度。首先按照杨辉三角的样子生成杨辉三角,并算出每个方块的值。首先打掉例如说9这个方块掉的值不是5所有掉的和6所有掉落的,那是因为5和6有重复的地方,所以不能直接那么计算,通过观察找规律发现,每个方块打掉一共掉落的数目是该列斜对角线的所有块。然后使用前缀和计算即可。例如说打8吧,第一个斜对角就是4,8前一行是2,5再前一行就是1,3。所以每个方块掉落值就是斜对角线所有的和。

代码

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#define x first
#define y second
#define endl '\n'
#define IOS                       \
    ios_base::sync_with_stdio(0); \
    cin.tie(0);                   \
    cout.tie(0);

using namespace std;

typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef unsigned long long ull;

const int INF = 0x3f3f3f3f, mod = 1000000007;
const int N = 2040;

ll a[N][N], b[N][N], d[N][N];
map<ll, pll> q;

void solve()
{
    ll cnt = 1, c = 1;
    for (int i = 1; i <= 2023; i++) {
        int j = 1;
        while (j <= i) {
            a[i][j] = cnt * cnt;
            q[cnt] = { i, j };
            cnt++;
            j++;
        }
    }
    d[1][1] = a[1][1];
    for(int i = 2; i <= 2023; i++){
        for(int j = 1; j <= i; j++){
            d[i][j] = d[i - 1][j - 1] + a[i][j];//计算每个方块斜对角线的方块值的和
        }
    }
    // cout << "--------------------\n";
    for(int i = 1; i <= 2023; i++){
        for(int j = 1; j <= i; j++){
            d[i][j] += d[i - 1][j];//然后求当前斜对角线上面的所有的和
        }
    }
}
int main()
{
    IOS;
    int t = 1;
    solve();
    cin >> t;
    while (t--) {
        int x;
        cin >> x;
        cout << d[q[x].x][q[x].y] << endl;
    }
    return 0;
}
最后修改:2023 年 05 月 11 日
如果觉得我的文章对你有用,请随意赞赏