An undirected graph is called a caterpillar if it is connected, has no cycles, and there is a path in the graph where every node is either on this path or a neighbor of a node on the path. This path is called the spine of the caterpillar and the spine may not be unique. You are simply going to check graphs to see if they are caterpillars.
For example, the left graph below is not a caterpillar, but the right graph is. One possible spine is
shown by dots.
Input
There will be multiple test cases. Each test case starts with a line containing n indicating the number of nodes, numbered 1 through n (a value of n = 0 indicates end-of-input). The next line will contain an integer e indicating the number of edges. Starting on the following line will be e pairs n1 n2 indicating an undirected edge between nodes n1 and n1. This information may span multiple lines. You may assume that n ≤ 100 and e ≤ 300. Do not assume that the graphs in the test cases are connected or acyclic.
Output
For each test case generate one line of output. This line should either be
Graph g is a caterpillar.
or
Graph g is not a caterpillar.
as appropriate, where g is the number of the graph, starting at 1.
Sample Input
22
21
1 2 2 3 2 4 2 5 2 6 6 7 6 10 10 8 9 10 10 12 11 12 12 13 12 17
18 17 15 17 15 14 16 15 17 20 20 21 20 22 20 19
16
15
1 2 2 3 5 2 4 2 2 6 6 7 6 8 6 9 9 10 10 12 10 11 10 14 10 13 13 16 13 15
0
Sample Output
Graph 1 is not a caterpillar.
Graph 2 is a caterpillar.
题目大意:
如果一个无向图是连通的,没有环,并且图中有一条路径,其中每个节点要么在这条路径上,要么在这条路径上的一个节点的邻居上,则称为毛虫图。
给定一个无向图,判断其是不是毛虫图。
核心思想:
先用并查集判断一个无向图是不是树,然后按照题意搜索。
代码如下:
#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
const int N=110;
vector<int>vec[N];
bool vis[N];
int pre[N],num[N];
int find(int x)
{
if(pre[x]==x)
return x;
return pre[x]=find(pre[x]);
}
//返回0表示已经连接在一起,再次连接会出现环
bool merge(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx==fy)
return 0;
if(num[fx]>num[fy])
{
pre[fy]=fx;
num[fx]+=num[fy];
}
else
{
pre[fx]=fy;
num[fy]+=num[fx];
}
return 1;
}
bool fun(int n)
{
int te=1;
vis[1]=1;
while(1)
{
int len=vec[te].size();
int cnt=0,ne;
for(int i=0;i<len;i++)
{
int t=vec[te][i];
if(vis[t])continue;
vis[t]=1;
if(vec[t].size()>1)
{
cnt++;
ne=t;
}
if(cnt>1)
return 0;
}
if(!cnt)
break;
te=ne;
}
return 1;
}
int main()
{
int n,m,x,y,ca=0;
while(1)
{
scanf("%d",&n);
if(!n)
break;
scanf("%d",&m);
for(int i=1;i<=n;i++)
{
vis[i]=0;
vec[i].clear();
pre[i]=i;
num[i]=1;
}
int flag=0,sum=0;
for(int i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
if(flag)continue;
vec[x].push_back(y);
vec[y].push_back(x);
if(!merge(x,y))
flag=1;
else
sum++;
}
//flag=1表示出现环,sum<n-1表示不连通
if(flag||sum<n-1)
{
printf("Graph %d is not a caterpillar.\n",++ca);
continue;
}
if(fun(n))
printf("Graph %d is a caterpillar.\n",++ca);
else
printf("Graph %d is not a caterpillar.\n",++ca);
}
return 0;
}