[event1] 赛题题解

· · 个人记录

T1题解

方法很多,可以用前缀和,也可以进行压缩。 这里采取压缩找规律的方法。

code
#include<iostream>
#define int long long
using namespace std;
int a[10000007];
signed main()
{
    int t, xb = 0, cnt, l, r, vis;
    cin >> t;
    for(int i = 1; xb < 10000000; i ++)
    {
        cnt = 0;
        for(int j = 1; j <= i && xb < 10000000; j ++)
        {
            a[i] += j;
            xb ++;
        }
    }
    for(int sb = 1; sb <= t; sb ++)
    {
        cin >> l >> r;
        xb = 0;
        int i; 
        for(i = 1; xb < l; i ++)
        {
            xb += i; 
        }
        xb = 0;
        int j;
        for(j = 1; xb < r; j ++)
        {
            xb += j; 
        }

        i --;
        j --;
        for(int k = 1; k < i; k ++)
        {
            l -= k;
        }
        for(int k = 1; k < j; k ++)
        {
            r -= k;
        }
        //此时i,j存储l,r的位置。
        int cnt = 0;
        for(int k = i; k <= j; k ++)
        {
            cnt += a[k];
        }
        for(int k = 1; k < l; k ++)
        {
            cnt -= k;
        }
        for(int k = r + 1; k <= j; k ++)
        {
            cnt -= k;
        }
        cout << cnt << endl;
    }
}

T2题解

题目要求求最优解,并且数据范围比较小,考虑使用BFS。按照要求,要字典序最小,所以可以将迭代顺序从DRLU换成DLRU,这样最先到达终点的方案也可以保证字典序最小。

```cpp // BFS #include <iostream> #include <queue> #include <string> #include <vector> using namespace std; int n, a[15][15]; bool vis[15][15]; int dir[4][2] = {{1, 0}, {0, -1}, {0, 1}, {-1, 0}}; char dirc[4] = {'D', 'L', 'R', 'U'}; struct Node { int x, y, step; //记录坐标、步数 string path; //记录路径 }; int main() { cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> a[i][j]; } } queue<Node> q; q.push({1, 1, 0, ""}); vis[1][1] = true; while (!q.empty()) { Node cur = q.front(); q.pop(); if (cur.x == n && cur.y == n) { cout << cur.step << endl; cout << cur.path << endl; return 0; } for (int i = 0; i < 4; i++) { int nx = cur.x + dir[i][0]; int ny = cur.y + dir[i][1]; if (nx >= 1 && nx <= n && ny >= 1 && ny <= n && a[nx][ny] == 0 && !vis[nx][ny]) { vis[nx][ny] = true; q.push({nx, ny, cur.step + 1, cur.path + dirc[i]}); } } } return 0; } ``` # T3题解 数字初始顺序很明显不影响结果,先考虑排个序。 考虑如下排序方法:用$sort$函数,自定义我们的排序方式,这里我们采取一种特殊的排序方法,如果两个数a,b,我们要考虑更大的结果,即判断a+b大还是b+a大(这里的相加指的是拼接,因为数据太大,我们只能用string存储)。 最后拼接输出即可。 $code
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// 自定义比较函数
bool compare(const string &a, const string &b) {
    return a + b > b + a;
}

int main() {
    int n;
    cin >> n;

    vector<string> nums(n);
    for (int i = 0; i < n; ++i) {
        cin >> nums[i];
    }

    // 使用自定义比较函数进行排序
    sort(nums.begin(), nums.end(), compare);

    // 拼接结果
    string result;
    for (const string &num : nums) {
        result += num;
    }

    cout << result << endl;

    return 0;
}