您的位置:首页 > 其它

UVALive 7661 The Size of the Smallest Hole(dfs)

2017-10-25 18:46 471 查看
7661 The Size of the Smallest Hole

A cycle in an undirected graph consists of a sequence of different vertices except the starting vertex

and the ending vertex, with each two consecutive vertices in the sequence being adjacent to each other

in the graph. The length of a cycle is the number of edges in the cycle. A hole in a graph is a cycle of

length greater than or equal to 3 such that no two vertices of the cycle are connected by an edge that

does not belong to the cycle. The size of a hole is the number of edges in the hole. You are asked to

determine the size of the smallest hole of a undirected graph.

Technical Specification

• The number of vertices in any given undirected graph is n, n ≤ 100.

• There are no parallel edges nor loops in any given graphs.

Input

In each problem instance, the first line contains the number of vertices, n, in a graph. The following

n lines contain the adjacent list of the graph. That is, line i contains the adjacent vertices of vertex i.

There is a whitespace between any two numbers in each line. There may be more than one problem

instance. A line containing a single ‘0’ indicates the end of test cases.

Output

For each test case, output the smallest hole size of the graph in a line. If there is no hole in the graph,

then output ‘0’ in a line.

Sample Input

5

2 4

1 3 4

2 4 5

1 2 3 5

3 4

4

2

1 3

2 4

3

8

2 8

1 3 4

2 5

2 6

3 8

4 7

6 8

1 5 7

0

Sample Output

3

0

5

题意:给一个图G,找G中是否存在最小环,若存在,输出环的大小

思路:

做法很多,可以删去 e(u,v)后求(u,v)的最短路

也可以dfs或者bfs

#include<bits/stdc++.h>
using namespace std;
vector<int> g[101];
int ans;
int vis[101];
int mp[101][101];

void dfs(int u,int f[],int last)
{
for(auto v:g[u])
{
if(last==v)continue;//如果上一个点是v的话,不用考虑
if(vis[v]==0)//若从未拜访过该点,就往下dfs
{
vis[v]=vis[u]+1;//该点的值等于上一个点的值+1
dfs(v,f,u);
vis[v]=0;//记得清零
}
else if(vis[v])//如果遇见一个已经拜访过的点,说明已经成环
{
ans = min(ans,vis[u]-vis[v]+1);
}
}
}

int main()
{
int n;
while(cin>>n&&n)
{
memset(mp,0,sizeof(mp));
memset(vis,0,sizeof(vis));
int v;
char c;
for(int i=1;i<=n;i++)
{
g[i].clear();
while(scanf("%d%c",&v,&c)!=EOF)
{
mp[i][v]=1;//建边
g[i].push_back(v);//建边
if(c=='\n')break;
}
}
ans=0x3f3f3f3f;
for(int i=1;i<=n-2;i++)
{
if(g[i].size()>1)
{
memset(vis,0,sizeof(vis));
vis[i]=1;//表示i是第 1 个点
dfs(i,vis,-1);
}
}
cout<<((ans==0x3f3f3f3f)?0:ans)<<endl;
}
return 0;
}


转载请注明出处^ ^
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs icpc