思路
写个不太一样的,二分答案的题解。
考虑二分
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN=20;
const int MAXM=11000;
const int MAXS=70000;
int n, m;
int a[MAXN][MAXM];
int c[MAXN], f[MAXN][MAXS];
bool chk1(int x, int y, int k)
{
for (int i=1; i<=m; i++)
if (abs(a[x][i]-a[y][i])<k) return 0;
return 1;
}
bool chk2(int x, int y, int k)
{
for (int i=1; i<m; i++)
if (abs(a[x][i+1]-a[y][i])<k) return 0;
return 1;
}
bool check(int k)
{
memset(c, 0, sizeof c);
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
if (chk1(i, j, k)) c[i]|=1<<j-1;
memset(f, 0, sizeof f);
for (int i=1; i<=n; i++)
for (int s=1; s<1<<n; s++)
{
if (!(s&1<<i-1)) continue;
if (s==1<<i-1) f[i][s]=1<<i-1;
else
{
for (int j=1; j<=n; j++)
if (s&1<<j-1&&f[i][s^1<<j-1]&c[j])
f[i][s]|=1<<j-1;
}
}
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++)
if (chk2(i, j, k)&&f[i][(1<<n)-1]&1<<j-1) return 1;
return 0;
}
int main()
{
// freopen("CF1102F.in", "r", stdin);
// freopen("CF1102F.out", "w", stdout);
scanf("%d%d", &n, &m);
for (int i=1; i<=n; i++)
for (int j=1; j<=m; j++)
scanf("%d", &a[i][j]);
int l=0, r=1E9;
while (l<r)
{
int mid=l+r+1>>1;
if (check(mid)) l=mid;
else r=mid-1;
}
printf("%d\n", l);
return 0;
}