题目链接
题意
定义了一个n*m的桌面,每一块有不同的颜色, 要求是求出每一对相同颜色的方块之间的曼哈顿距离之和。曼哈顿距离是指,只有相邻(有共同的边)才可以移动的条件下,两者之间的最短距离
思路
可以用vector来记录,行和列分开来计算。使用 sum[] 数组 和 cnt[]数组 sum[x]记录x颜色的横(纵)坐标之和 cnt[x]记录x颜色出现的次数。我们使用变量ans来表示曼哈顿距离的和,先算所有行,再算所有列。以计算横坐标之差为例。
首先 xi与前面其他的坐标之差的和可以表示成:
xi*(i-1) - (x1+...+xi-1)
这样 我们就可以就可以计算出各个坐标与前面的坐标的差值之和,也就可以计算出两个颜色相同的横坐标的距离
代码
#include<map>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#define Endl "\n"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 1e6+5;
const int INF = 0x3f3f3f;
const int mod = 1e9 + 7;
const double pi = acos(-1);
inline ll read(){
ll x = 0, f = 1; char ch; ch = getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
ll n,m,ans;
ll sum[maxn],cnt[maxn];
vector <int> mp[maxn];
void solve() {
n=read(),m=read();
ans=0;
memset(sum,0,sizeof(sum));
memset(cnt,0,sizeof(cnt));
//行
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
int x;
x=read();
mp[i].push_back(x);
ans+=cnt[x]*i-sum[x];
sum[x]+=i;
cnt[x]++;
}
}
memset(sum,0,sizeof(sum));
memset(cnt,0,sizeof(cnt));
//列
for(int j=1;j<=m;j++)
{
for(int i=1;i<=n;i++)
{
int x=mp[i][j-1];
ans+=cnt[x]*j-sum[x];
sum[x]+=j;
cnt[x]++;
}
}
cout<<ans<<Endl;
return ;
}
int main() {
// for(int T = read(); T; T--)
solve();
return 0;
}