本文已参与「新人创作礼」活动,一起开启掘金创作之路。
题目
Instruction: Let G=(V,E) be a connected graph. An edge(u,v) is a bridge to GifG'=(V,E\{(u,v)}) is disconnected. In other words,G becomes disconnected after removing the edge(u,v). For example,
in the graph above,(4,5) and(6,8) are bridges.
Design and implement an algorithm to find all bridges for a given graph. Your algorithm runs in O(n2) time.
This is an individual assignment. Copying is not allowed.
Documentation(40%):
- You need to present your algorithm as pseudocodes.
- Analyze the time complexity of your algorithm.
- Explain why your algorithm is correct.
- Explain a method to reduce the time complexity to O(e).(You don't need to implement this in your program because of some reasons.)
- Write these in a Word document. Implementation(60%): 1.Implement your algorithm in C programming language.(You can use PellesC or Mingw or Cygwin or Xcode or www.onlinegdb.com.Please don't use Visual Studio. My computer is too weak.) 2.Your program reads a graph from“in.txt”. 3.The input file“in.txt”follows this format. a.The first line consists of one integer,the number of vertices in the graph. b.The index of vertices starts from 1. c.The second line to the last line is the adjacency matrix of the graph.d.The adjacency matrix is an 0-1 matrix.Two vertices are adjacent if the corresponding entry is 1. e. You can assume the input file format is robust. So, you don't need to test if the input file is in the correct format.
- Print all bridges of the graph on the screen. Ifthe graph has no bridge, print"No bridge."
- For example, the above graph is represented as
6. And the expected output is"(4,5)(6,8)".
解析
从某一点出发,dfs能够找到联通的最大区域,已知是联通图,无论从那个点出发,dfs都能得到最大联通区域,如果去掉某条边,最大联通区域减小,则该条边是桥。
核心代码
void cal()
{
for(int i=0; i<sum; i++)
{
for(int j=i+1; j<sum; j++)
{
if(Matrix[i][j]==1)
{
Matrix[i][j]=0;
Matrix[j][i]=0;
for(int k=0; k<sum; k++)
{
visited[k]=0;
}
dfs(0);
for(int k=0; k<sum; k++)
{
if(visited[k]==0)
{
printf("(%d,%d)",i+1,j+1);
break;
}
}
Matrix[i][j]=1;
Matrix[j][i]=1;
}
}
}
}
int main()
{
read_txt("in.txt");
cal();
return 0;
}
问答题
对全图做DFS需要O(n+e)
有e条边
需要对全图做e次DFS,总时间为O(en+e²)
(其他题目见资源)
传送门
两个版本的代码,直接跑就行,包括问答题答案
download.csdn.net/download/re…