跳到正文

个人记录

【HT-110-Div.4】核桃新手组周赛

senuo约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年5月8日
收录
2026年5月16日
更新
2026年11月15日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

C:P11972 摊位编号

思路

给定 nn 个长度均为 mm 的字符串,两个字符串之间的差异值定义为对应位置字母差的绝对值之和(因为每一步只能将字母改成相邻字母,恰好等于直接改变的距离)。要求所有字符串两两之间差异值的最小值。

数据范围 n≤1000n \le 1000,m≤50m \le 50,两两组合约 5×1055\times10^5 对,每对计算 mm 次,总运算量约 2.5×1072.5\times10^7,在时限内完全可行。直接二重循环枚举所有字符串对,计算差异值并更新最小值即可。

核心代码

C++
int ans = 1e9;
for (int i = 0; i < n; ++i) {
    for (int j = i + 1; j < n; ++j) {
        int diff = 0;
        for (int k = 0; k < m; ++k)
            diff += abs(s[i][k] - s[j][k]);
        if (diff < ans) ans = diff;
    }
}
cout << ans;

完整代码

C++
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 1005;
char s[MAXN][55];

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; ++i)
        cin >> s[i];

    int ans = 1e9;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            int diff = 0;
            for (int k = 0; k < m; ++k)
                diff += abs(s[i][k] - s[j][k]);
            if (diff < ans) ans = diff;
        }
    }
    cout << ans << '\n';
    return 0;
}

D:P11881 边境巡逻

思路

正方形边长为 nn,两点均在边界上。沿边界走动的最短距离实际上是两点在周长上的弧长差与另一段弧长的较小值。将边界展开成一维:从 (0,0)(0,0) 出发顺时针行走,路上每一点都有一个累积距离。设函数 pos(x,y)pos(x,y) 返回该点对应的距离:

  • 若在底边 y=0y=0:pos=xpos = x
  • 若在右边 x=nx=n:pos=n+ypos = n + y
  • 若在顶边 y=ny=n:pos=2n+(n−x)pos = 2n + (n - x)
  • 若在左边 x=0x=0:pos=3n+(n−y)pos = 3n + (n - y)

计算两点的 pospos 值,差值的绝对值 dd 即为一段弧长,另一段弧长为周长 4n4n 减去 dd,最短距离即为 min⁡(d,4n−d)\min(d, 4n-d)。注意所有运算在整数范围内。

核心代码

C++
int get_pos(int n, int x, int y) {
    if (y == 0) return x;
    if (x == n) return n + y;
    if (y == n) return 2 * n + (n - x);
    return 3 * n + (n - y);
}

int d = abs(pos1 - pos2);
int ans = min(d, 4 * n - d);
cout << ans;

完整代码

C++
#include <bits/stdc++.h>
using namespace std;

int get_pos(int n, int x, int y) {
    if (y == 0) return x;
    if (x == n) return n + y;
    if (y == n) return 2 * n + (n - x);
    return 3 * n + (n - y);
}

int main() {
    int n, x1, y1, x2, y2;
    cin >> n >> x1 >> y1 >> x2 >> y2;
    int pos1 = get_pos(n, x1, y1);
    int pos2 = get_pos(n, x2, y2);
    int d = abs(pos1 - pos2);
    int ans = min(d, 4 * n - d);
    cout << ans << '\n';
    return 0;
}
原文