无双图求割顶的个数,Tarjan模板。
我这里有两种模板,似乎第一种比较简单。
CODE1:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using
namespace std;
#define MAXN 110
#define MAXM 10010
struct Edge
{
int v, next;
}edge[MAXM];
int first[MAXN];
int dfn[MAXN], low[MAXN];
int sub[MAXN];
//
保存的删除该节点之后,图分散变成子图的数量。
int n;
int cnt, tot;
int u, v;
inline
void init()
{
cnt =
0;
tot =
0;
memset(first, -
1,
sizeof(first));
memset(dfn,
0,
sizeof(dfn));
memset(sub,
0,
sizeof(sub));
}
inline
void read_graph(
int u,
int v)
{
edge[cnt].v = v;
edge[cnt].next = first[u], first[u] = cnt++;
}
inline
void read_graph2()
{
while(scanf(
"
%d
", &u) && u)
{
while(getchar() !=
'
\n
')
{
scanf(
"
%d
", &v);
read_graph(u, v);
read_graph(v, u);
}
}
}
void Tarjan(
int u)
//
不直接判断是否为根,而是将root的sub值赋值为0
{
dfn[u] = low[u] = ++tot;
for(
int e = first[u]; e != -
1; e = edge[e].next)
{
int v = edge[e].v;
if(!dfn[v])
{
Tarjan(v);
low[u] = min(low[u], low[v]);
if(dfn[u] <= low[v]) sub[u]++;
}
low[u] = min(low[u], dfn[v]);
}
}
void solve(
int root)
{
int ans =
0;
for(
int i =
1; i <= n; i++) sub[i] = (i == root)?
0:
1;
Tarjan(root);
for(
int i =
1; i <= n; i++)
{
if(sub[i] >
1) ans++;
//
若大于1,则说明是割顶。
}
printf(
"
%d\n
", ans);
}
int main()
{
while(scanf(
"
%d
", &n) && n)
{
init();
read_graph2();
solve(
1);
}
return
0;
}
CODE2:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using
namespace std;
struct Edge
{
int v, next;
}edge[
10001];
int first[
101];
int dfn[
101], low[
101];
int sub[
101];
int n;
int cnt, tot, root =
1;
int u, v;
inline
void init()
{
cnt =
0;
tot =
0;
memset(first, -
1,
sizeof(first));
memset(dfn,
0,
sizeof(dfn));
}
inline
void read_graph(
int u,
int v)
{
edge[cnt].v = v;
edge[cnt].next = first[u], first[u] = cnt++;
}
inline
void read_graph2()
{
while(scanf(
"
%d
", &u) && u)
{
while(getchar() !=
'
\n
')
{
scanf(
"
%d
", &v);
read_graph(u, v);
read_graph(v, u);
}
}
}
void Tarjan(
int u,
int fa)
//
处理的时候判断是否为根。
{
int rootson =
0;
low[u] = dfn[u] = ++tot;
for(
int e = first[u]; e != -
1; e = edge[e].next)
{
int v = edge[e].v;
if(!dfn[v])
{
if(u == root)
{
if(++rootson >
1) sub[u]++;
}
Tarjan(v, u);
low[u] = min(low[u], low[v]);
if(u != root && dfn[u] <= low[v]) sub[u]++;
}
low[u] = min(low[u], dfn[v]);
}
}
void solve()
{
int ans =
0;
for(
int i =
1; i <= n; i++) sub[i] =
1;
Tarjan(root, -
1);
for(
int i =
1; i <= n; i++)
{
if(sub[i] >
1) ans++;
}
printf(
"
%d\n
", ans);
}
int main()
{
while(scanf(
"
%d
", &n) && n)
{
init();
read_graph2();
solve();
}
return
0;
}