Problem UVALive - 3211 - Now or later
Time Limit: 9000 mSec
Problem Description
Input
Output
Sample Input
10 44 156 153 182 48 109 160 201 55 186 54 207 55 165 17 58 132 160 87 197
Sample Output
10
题解:2-SAT问题板子题,这个问题主要是理论难度比较大,有了结论之后代码很容易,有专门的论文阐释算法的正确性,看了几位大佬写的,基本上明白是怎么一回事,理解不深刻,就不在这里胡扯了,直接上代码。
#include <bits/stdc++.h> using namespace std; #define REP(i, n) for (int i = 1; i <= (n); i++)
#define sqr(x) ((x) * (x)) const int maxn = + ;
const int maxm = + ;
const int maxs = + ; typedef long long LL;
typedef pair<int, int> pii;
typedef pair<double, double> pdd; const LL unit = 1LL;
const int INF = 0x3f3f3f3f;
const LL mod = ;
const double eps = 1e-;
const double inf = 1e15;
const double pi = acos(-1.0); struct TwoSAT
{
int n;
vector<int> G[maxn * ];
bool mark[maxn * ];
int S[maxn * ], c; bool dfs(int x)
{
if (mark[x ^ ])
return false;
if (mark[x])
return true;
mark[x] = true;
S[c++] = x;
for (auto v : G[x])
{
if (!dfs(v))
return false;
}
return true;
} void init(int n)
{
this->n = n;
for (int i = ; i < n * ; i++)
{
G[i].clear();
}
memset(mark, , sizeof(mark));
} void add_clause(int x, int xval, int y, int yval)
{
x = x * + xval;
y = y * + yval;
G[x ^ ].push_back(y);
G[y ^ ].push_back(x);
} bool solve()
{
for (int i = ; i < n * ; i += )
{
if (!mark[i] && !mark[i + ])
{
c = ;
if (!dfs(i))
{
while (c > )
{
mark[S[--c]] = false;
}
if (!dfs(i + ))
return false;
}
}
}
return true;
}
}; TwoSAT solver; int n, T[maxn][]; bool Judge(int lim)
{
solver.init(n);
for (int i = ; i < n; i++)
{
for (int a = ; a < ; a++)
{
for (int j = i + ; j < n; j++)
{
for (int b = ; b < ; b++)
{
if (abs(T[i][a] - T[j][b]) < lim)
{
solver.add_clause(i, a ^ , j, b ^ );
}
}
}
}
}
return solver.solve();
} main()
{
ios::sync_with_stdio(false);
cin.tie();
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
while (cin >> n && n)
{
int le = , ri = ;
for (int i = ; i < n; i++)
{
for (int j = ; j < ; j++)
{
cin >> T[i][j];
ri = max(ri, T[i][j]);
}
} int ans = ;
while (le <= ri)
{
int mid = (le + ri) >> ;
if (Judge(mid))
{
ans = mid;
le = mid + ;
}
else
{
ri = mid - ;
}
}
cout << ans << endl;
}
return ;
}