#Description
有nm的阵
nn个人
每行n个,分散在不同的位置
然后他们要组成一个n*n的方阵,问最小移动总和
#Algorithm
先对每行为位置排序
然后枚举每个列 i
每行的第一个肯定是 在 i 最短
第二个在 i + 1最短
#Code
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 56 + 9;
int a[maxn][maxn];
int main()
{
int n, m;
for (;;)
{
scanf("%d%d", &n, &m);
if (n == 0 && m == 0) break;
memset(a, 0, sizeof(a));
for (int i = 0; i < n * n; i++)
{
int x, y;
scanf("%d%d", &x, &y);
a[x][++a[x][0]] = y;
}
for (int i = 1; i <= n; i++)
sort(a[i] + 1, a[i] + n + 1);
int ans = 1000000;
int ansi = 0;
for (int i = 1; i <= m; i++)
{
int tt = 0;
for (int j = 1; j <= n; j++)
for (int k = 1; k <= a[j][0]; k++)
tt += abs(a[j][k] - (i + k - 1));
if (tt < ans)
{
ansi = i;
ans = tt;
}
}
cout << ans << endl;
}
}