考虑比较暴力的方法,我们枚举两个集合的最大值S1, S2,那么我们可以用2-SAT来判断合法不合法(如果i, j之间的值大于S1,那么如果i在第一个集合,j只能在第二个集合,其他类似)。
我们将边权从大到小排序,依次枚举S1,发现S2是单调的(S2越大,越可能合法),于是可以二分S2了。
另外还有个优化,把枚举S1的过程看成加边的过程,我们发现当这个图不是二分图的时候就可以停止枚举了。
令m = n * n,C为最大边权,复杂度为O(mlogm + 玄学*(m + n)logC)
/* Think Thank Thunk */
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 205, maxm = maxn << 1, inf = 0x3f3f3f3f;
int n, m, A[maxn][maxn], fa[maxn], d[maxn];
int head[maxm], cnt, dfn[maxm], low[maxm], belong[maxm], tot, clo, sta[maxm], top;
bool ins[maxm];
struct edge {
int u, v, w;
bool operator < (const edge &x) const {
return w != x.w ? w > x.w : u != x.u ? u > x.u : v > x.v;
}
} e[maxn * maxn];
struct _edge {
int v, next;
} g[maxm * maxm];
inline int iread() {
int f = 1, x = 0; char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return f * x;
}
inline void add(int u, int v) {
g[cnt] = (_edge){v, head[u]};
head[u] = cnt++;
}
inline int find(int x) {
if(fa[x] == x) return x;
int res = find(fa[x]);
d[x] ^= d[fa[x]];
return fa[x] = res;
}
inline void tarjan(int x) {
dfn[x] = low[x] = ++clo;
ins[sta[++top] = x] = 1;
for(int i = head[x]; ~i; i = g[i].next) {
int v = g[i].v;
if(!dfn[v]) tarjan(v), low[x] = min(low[x], low[v]);
else if(ins[v]) low[x] = min(low[x], dfn[v]);
}
if(dfn[x] == low[x]) {
tot++;
while(1) {
int u = sta[top--];
belong[u] = tot;
ins[u] = 0;
if(u == x) break;
}
}
}
inline bool check(int S1, int S2) {
for(int i = n << 1; i; i--) head[i] = -1, dfn[i] = low[i] = belong[i] = ins[i] = 0; cnt = clo = tot = 0;
for(int i = 1; i <= n; i++) for(int j = i + 1; j <= n; j++) {
if(A[i][j] > S1) {
add((i << 1) - 1, j << 1);
add((j << 1) - 1, i << 1);
}
if(A[i][j] > S2) {
add(i << 1, (j << 1) - 1);
add(j << 1, (i << 1) - 1);
}
}
for(int i = n << 1; i; i--) if(!dfn[i]) tarjan(i);
for(int i = 1; i <= n; i++) if(belong[(i << 1) - 1] == belong[i << 1]) return 0;
return 1;
}
inline int calc(int c) {
int l = 0, r = c;
while(l <= r) {
int mid = l + r >> 1;
if(check(c, mid)) r = mid - 1;
else l = mid + 1;
}
return l;
}
int main() {
n = iread();
if(n <= 2) {
printf("0\n");
return 0;
}
for(int i = 1; i <= n; i++) for(int j = i + 1; j <= n; j++) {
A[i][j] = A[j][i] = iread();
e[++m] = (edge){i, j, A[i][j]};
}
for(int i = 1; i <= n; i++) fa[i] = i, d[i] = 0;
sort(e + 1, e + m + 1);
int ans = inf;
for(int i = 1; i <= m; i++) {
int u = e[i].u, v = e[i].v, w = e[i].w;
if(find(u) != find(v)) {
int x = find(u), y = find(v);
ans = min(ans, w + calc(w));
d[x] = d[u] ^ d[v] ^ 1;
fa[x] = y;
} else if(d[u] == d[v]) {
ans = min(ans, w + calc(w));
break;
}
}
printf("%d\n", ans);
return 0;
}