A. Weird Sum - 思维

题面

分析

所有点的曼哈顿距离可以分解成所有点的任意横坐标之间的距离,以及所有任意纵坐标的距离,对于处理所有点的距离,可以利用线段的思想,将所有点排序,第一个点很显然不用处理,第二个点需要求的距离有第二个点到第一个点的距离,第三个点需要处理到第一个点的距离,以及到第二个点的距离。

代码
cpp 复制代码
#include <bits/stdc++.h>

#define int long long

using namespace std;

const int N = 1e5 + 10;

vector<int> a[N], b[N];

void solve() {
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= 1e5; i ++) a[i].clear(), b[i].clear();
    for(int i = 0; i < n; i ++) {
        for(int j = 0; j < m; j ++) {
            int x;
            cin >> x;
            a[x].push_back(i);
            b[x].push_back(j);
        }
    }
    int ans = 0;
    for(int i = 1; i <= 1e5; i ++) {
        sort(a[i].begin(), a[i].end());
        sort(b[i].begin(), b[i].end());
        int s = 0;
        for(int j = 0; j < a[i].size(); j ++) {
            ans += j * a[i][j] - s;
            s += a[i][j];
        }
        s = 0;
        for(int j = 0; j < b[i].size(); j ++) {
            ans += j * b[i][j] - s;
            s += b[i][j];
        }
    }
    cout << ans << "\n";
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    T = 1;//cin >> T;
    while(T --) {
        solve();
    }
}
相关推荐
生态学者7 小时前
Global Change Biology | 森林越“步调一致”,反而越怕干旱?树木生长与叶片活动的同步之谜
大数据·人工智能·算法·r语言·微信公众平台
所以遗憾是什么呢?7 小时前
【题解】Educational Codeforces Round 195 (Rated for Div. 2) ABCDE
c++·动态规划·acm·icpc·ccpc·xcpc·codeforecs
lsswear8 小时前
Agent 框架新手入门与实战部署指南
大数据·人工智能·算法
Lhan.zzZ9 小时前
Qt WebEngineView 在 Linux 上无法加载网页:从“看不见 HTML“到“禁用沙箱“
linux·c++·qt
Data analyse45610 小时前
rnweb 回放数据量太大怎么办?分片存储与断点续传的实现思路
前端·网络·算法·数据分析
sysu_chenxy11 小时前
二重循环输出二维图形
c++
Navigator_Z11 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil20811 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年11 小时前
AI Agent、自动化与未来工作
人工智能·算法·架构
牧羊人.33312 小时前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉