跳到正文

题解

题解:P13543 [OOI 2022] Strange sum

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

文章信息

收录
2025年12月12日
更新
2026年2月6日
篇幅
约 4 分钟
获赞
1
题目
P13543

版本

  1. v1当前

这是一个计算颜色相同格子间曼哈顿距离总和的问题。我们可以通过分组计算每个颜色的所有格子坐标,然后分别计算它们的曼哈顿距离总和

简单!!!

c++代码:

C++
#include<bits/stdc++.h>
using namespace std;
#define TLE ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int main() {
    TLE
    int n, m;
    cin >> n >> m;
    map<int, vector<pair<int, int> > > color_map;
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            int color;
            cin >> color;
            color_map[color].emplace_back(i, j);
        }
    }
    long long total = 0;
    for (auto& [color, coords] : color_map) {
        // 按行排序计算行贡献
        sort(coords.begin(), coords.end());
        long long prefix_sum = 0;
        for (int i = 0; i < coords.size(); ++i) {
            total += (long long)coords[i].first * i - prefix_sum;
            prefix_sum += coords[i].first;
        }
        // 按列排序计算列贡献
        sort(coords.begin(), coords.end(), [](auto& a, auto& b) {
            return a.second < b.second;
        });
        prefix_sum = 0;
        for (int i = 0; i < coords.size(); ++i) {
            total += (long long)coords[i].second * i - prefix_sum;
            prefix_sum += coords[i].second;
        }
    }
    cout << total << endl;
    return 0;
}

代码说明:

1.使用map按颜色分组存储所有格子的坐标

2.对每个颜色分别计算行方向和列方向的曼哈顿距离总和

3.通过排序和前缀和优化计算,将O(n²)复杂度降为O(nlogn)

4.总时间复杂度为O(nmlog(nm)),适用于大规模数据

这个问题是关于计算颜色相同格子间曼哈顿距离总和的问题。我将详细解释代码的实现原理和优化思路:

输入处理: 使用快速输入方法(ios::sync_with_stdio)加速读取 使用map按颜色分组存储所有格子的坐标

核心算法: 曼哈顿距离可以分解为行方向和列方向的距离之和 对每个颜色分别计算行方向和列方向的贡献

通过排序和前缀和优化计算: 先按行坐标排序,计算行方向距离和 再按列坐标排序,计算列方向距离和

数学原理: 对于排序后的坐标序列x₁,x₂,…,xₙ 两两距离和 = Σ(xⱼ - xᵢ) = Σxⱼ*(j-1) - Σxᵢ*(n-i) 使用前缀和可以O(n)计算这个值

复杂度分析: 分组存储O(nm) 排序O(klogk)其中k是每组点数 前缀和计算O(k) 总复杂度O(nmlog(nm))

优化点: 使用long long防止溢出 使用emplace_back减少拷贝 使用lambda表达式自定义排序

输出: 累加所有颜色的距离和输出

这个解法巧妙地利用了曼哈顿距离的可分解性和排序前缀和优化,将O(n²)的暴力计算优化为O(nlogn)的高效算法。 5.使用long long防止整数溢出

原文