A. Weird Sum

A. Weird Sum

在这里插入图片描述

Examples

input

2 3
1 2 3
3 2 1

output

7

input

3 4
1 1 2 2
2 1 1 2
2 2 1 1

output

76

input

4 4
1 1 2 3
2 1 1 2
3 1 2 1
1 1 2 1

output

129

Note

In the first sample there are three pairs of cells of same color: in cells (1,1)and(2,3), in cells(1,2) and (2,2), in cells (1,3)and(2,1). The manhattan distances between them are 3, 1 and 3, the sum is 7.

一道想了两天的题目。

题目大意:

一个n*m的矩阵,求所有相同元素之间的曼哈顿距离之和。

思路:

先把相同的数字分到一组,因为曼哈顿距离等于|xi-xj|+|yi-yj|,所以可以把x和y分别计算,不妨先抽离出每个数的x坐标,那么问题就变成了求 x1 x2 … xn 中两两距离的和。(快速求这个和让我想了好久)。

先考虑简单的情况,当x中,没有重复的数时,答案就是相邻两数差的前缀和。

比如 1 3 5 7 11 那么差就是 2 2 2 4 前缀和就是 2 4 6 10

但是实际上是有重复数字的,不方便直接算,可以反着算。

比如 1 1 2 2 3 4 我们算3对3之前的数的贡献,3-1+3-1+3-2+3-2=6

其实就是3*4-1-1-2-2,也就是 当前的数 * 前面的数的个数 - 前缀和

那么答案就出来了,ans += xi * (i - 1) * sum(i - 1)

代码:
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
#include<map>
#define endl '\n'
using namespace std;
const int N=1e6+7;

map<int,vector<int>>mp1,mp2;

long long solve(map<int,vector<int>>&s)
{
    long long ans=0;
    for(auto temp:s)
    {
        auto v=temp.second;
        sort(v.begin(),v.end());
        long long sum=0;//前缀和
        long long count=0;//统计元素数量
        for(auto j:v)
        {
            ans+=j*count-sum;
            sum+=j;
            count++;
        }
    }
    return ans;
}

int main()
{
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int n,m;
    cin>>n>>m;
    for(int i=0;i<n;++i)
    {
        for(int j=0;j<m;++j)
        {
            int a;
            cin>>a;
            mp1[a].push_back(i);
            mp2[a].push_back(j);
        }
    }
    cout<<solve(mp1)+solve(mp2)<<endl;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值