思路
無向圖求割點裸題,直接tarjan生成一顆深度優先生成樹。判斷當前子節點能不能返回到父節點的父節點或者更遠,也就是能回到除去父節點之外更遠的祖先。
- 如果子節點能回到祖先說明父節點不是割點,去掉父節點這個圖依然連通。
- 如果子節點不能回到祖先,說明父節點是割點,去掉父節點這個連通圖被分成2個以上的連通塊。
這題除了輸入有點噁心之外其他的沒啥,搞不動爲啥要這樣輸入。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <string>
#include <vector>
using namespace std;
struct edge{
int to;
int next;
}e[500];
int head[105];
int dfn[105]; //節點的訪問順序
int low[105]; //子節點能回到祖先的序號
bool cut[105]; //割點
int n,cnt,tot,ans;
inline void clear_set()
{
cnt = tot = ans = 0;
memset(head,-1,sizeof(head));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(cut,false,sizeof(cut));
}
inline void addedge(int x,int y)
{
e[tot].to = y;
e[tot].next = head[x];
head[x] = tot++;
}
inline void tarjan(int x,int fx)
{
dfn[x] = low[x] = ++cnt;
int child = 0;
for(int i = head[x];~i;i = e[i].next){
int y = e[i].to;
if(!dfn[y]){
child++;
tarjan(y,x);
low[x] = min(low[x],low[y]);
if(low[y] >= dfn[x] && x != 1){
if(!cut[x]){
ans++;
}
cut[x] = true;
}
}
else if(dfn[y] < dfn[x] && y != fx){
low[x] = min(low[x],dfn[y]);
}
}
if(child >= 2 && x == 1){
if(!cut[x]){
ans++;
}
cut[x] = true;
}
}
int main()
{
while(~scanf("%d",&n) && n){
clear_set();
int x,y;
while(scanf("%d",&x) && x != 0){
while(getchar() != '\n'){
scanf("%d",&y);
addedge(x,y);addedge(y,x);
}
}
tarjan(1,-1);
printf("%d\n",ans);
}
return 0;
}
願你走出半生,歸來仍是少年~