题意:求割点,并求出去掉每个割点图会被分成几个连通分支。
分析:求割点除了tarjan算法,还有一种O(n^2)的算法,就是分别把每个点作为根,进行dfs,看根有几个子结点,如果大于一个则为割点否则不是割点。本题就是观察每个点为根时有几个子结点,去掉该点后的连通分支数等于其子结点数。
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
#define maxn 1005
struct Edge
{
int v, next;
} edge[maxn * maxn];
int id[maxn];
int name[maxn];
int head[maxn];
int n;
int ecount;
bool vis[maxn];
int cnt;
void addedge(int a, int b)
{
edge[ecount].v = b;
edge[ecount].next = head[a];
head[a] = ecount++;
}
int getid(int a)
{
if (id[a] == -1)
{
n++;
id[a] = cnt;
name[cnt] = a;
cnt++;
}
return id[a];
}
void make(int a, int b)
{
int aa = getid(a);
int bb = getid(b);
addedge(aa, bb);
addedge(bb, aa);
}
void dfs(int u)
{
vis[u] = true;
for (int i = head[u]; i != -1; i = edge[i].next)
if (!vis[edge[i].v])
dfs(edge[i].v);
}
int cal(int a)
{
int ret = 0;
memset(vis, 0, sizeof(vis));
vis[a] = true;
for (int i = head[a]; i != -1; i = edge[i].next)
if (!vis[edge[i].v])
{
dfs(edge[i].v);
ret++;
}
return ret;
}
int main()
{
//freopen("t.txt", "r", stdin);
int a, b, t = 0;
while (scanf("%d", &a), a)
{
t++;
printf("Network #%d\n", t);
memset(id, -1, sizeof(id));
memset(head, -1, sizeof(head));
n = 0;
ecount = 0;
cnt = 0;
do
{
scanf("%d", &b);
make(a, b);
} while (scanf("%d", &a), a);
bool did = false;
for (int i = 0; i < n; i++)
{
int temp = cal(i);
if (temp > 1)
{
did = true;
printf(" SPF node %d leaves %d subnets\n", name[i], temp);
}
}
if (!did)
printf(" No SPF nodes\n");
putchar('\n');
}
return 0;
}