题意
传送门 POJ 2942 Knights of the Round Table
题解
建出补图,即没有仇恨的两个骑士间连边,问题转化为求图中不被任何奇环包含的节点数量。
无论是 e − D C C e-DCC e−DCC 或 v − D C C v-DCC v−DCC 都满足在同一环上的两个节点位于相同的双连通分量。否则,将与双连通分量的极大性矛盾。
若图中存在奇环,则图不是二分图,可以用 D F S DFS DFS 的染色法判定,但并不能求出所有的奇环。同一个 e − D C C e-DCC e−DCC 中两个不同的环至少存在一个交点;而同一个 v − D C C v-DCC v−DCC 中两个不同的环至少存在两个节点,即至少存在一条边,那么某个环被交点划分为两条长度分别为奇数与偶数的边。
引理:若某个 v − D C C v-DCC v−DCC 中存在奇环,则这个 v − D C C v-DCC v−DCC 中的所有点都被至少一个奇环包含。
那么用 T a r j a n Tarjan Tarjan 算法求出补图中所有的 v − D C C v-DCC v−DCC,判定各个 v − D C C v-DCC v−DCC 是否存在奇环即可。
v − D C C v-DCC v−DCC 与 e − D C C e-DCC e−DCC 不同,不能简单地通过求出割点后 D F S DFS DFS 求解,因为 v − D C C v-DCC v−DCC 可能仅由割点构成,同一个割点可能被多个 v − D C C v-DCC v−DCC 包含。应该在 T a r j a n Tarjan Tarjan 算法中维护一个栈,当一个节点第一次被访问时,将节点入栈;当割点判定的条件 l o w [ y ] ≥ d f n [ x ] low[y]\geq dfn[x] low[y]≥dfn[x] 成立时,无论 x x x 是否为根,都要不断弹栈,直至 y y y 节点被弹出,此时弹出的所有节点与 x x x 构成一个 v − D C C v-DCC v−DCC。
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1005, maxm = 1000005;
int N, M, num, dfn[maxn], low[maxn];
int tot, head[maxn], to[maxm], nxt[maxm];
int top, st[maxn], nr, rec[maxn];
int dcc, dc[maxn], col[maxn];
bool in[maxn], G[maxn][maxn];
void init()
{
num = tot = dcc = top = 0;
memset(in, 0, sizeof(in));
memset(G, 0, sizeof(G)), memset(head, 0, sizeof(head));
memset(dfn, 0, sizeof(dfn)), memset(dc, 0, sizeof(dc));
}
inline void add(int x, int y) {
to[++tot] = y, nxt[tot] = head[x], head[x] = tot; }
bool find(int x, int c)
{
col[x] = c;
for (int i = head[x]; i; i = nxt[i])
{
int y = to[i];
if (dc[y] != dcc)
continue;
if (!col[y])
{
if (find(y, -c))
return 1;
}
else if (col[y] == c)
return 1;
}
return 0;
}
void tarjan(int x, int rt)
{
dfn[x] = low[x] = ++num;
st[++top] = x;
for (int i = head[x]; i; i = nxt[i])
{
int y = to[i];
if (!dfn[y])
{
tarjan(y, rt);
low[x] = min(low[x], low[y]);
if (low[y] >= dfn[x])
{
int sum = 1, z;
++dcc, nr = 0;
rec[++nr] = x, dc[x] = dcc;
do
{
z = st[top--], rec[++nr] = z, dc[z] = dcc, ++sum;
} while (z != y);
if (sum >= 3)
{
for (int j = 1; j <= nr; ++j)
col[rec[j]] = 0;
if (find(x, 1))
for (int j = 1; j <= nr; ++j)
in[rec[j]] = 1;
}
}
}
else
low[x] = min(low[x], dfn[y]);
}
}
int main()
{
while (~scanf("%d%d", &N, &M) && (N | M))
{
init();
for (int i = 1, x, y; i <= M; ++i)
scanf("%d%d", &x, &y), G[x][y] = G[y][x] = 1;
for (int i = 1; i <= N; ++i)
for (int j = i + 1; j <= N; ++j)
if (!G[i][j])
add(i, j), add(j, i);
for (int i = 1; i <= N; ++i)
if (!dfn[i])
tarjan(i, i);
int res = N;
for (int i = 1; i <= N; ++i)
res -= in[i];
printf("%d\n", res);
}
return 0;
}