Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 300300 points
Problem Statement
You are given a simple undirected graph with NN vertices numbered 11 to NN and MM edges numbered 11 to MM. Edge ii connects vertex u_iui and vertex v_ivi.
Find the number of connected components in this graph.
Notes
A simple undirected graph is a graph that is simple and has undirected edges.
A graph is simple if and only if it has no self-loop or multi-edge.
A subgraph of a graph is a graph formed from some of the vertices and edges of that graph.
A graph is connected if and only if one can travel between every pair of vertices via edges.
A connected component is a connected subgraph that is not part of any larger connected subgraph.
Sample Input 1 Copy
Copy5 3 1 2 1 3 4 5
Sample Output 1 Copy
Copy2
The given graph contains the following two connected components:
- a subgraph formed from vertices 11, 22, 33, and edges 11, 22;
- a subgraph formed from vertices 44, 55, and edge 33.
题目大意:求极大连通子图的连通分量,DFS图的遍历;
做法:创建一个无向图,图中存储每一行的行号能够到达的点。
如题目中给的样例,创建一个无向图
1 2 3 4 5
1 2 3
2 1
3 1
4 5
5 4
这里我建议用二维向量,这样开辟的空间少,可以不用处理未被标记的点,然后dfs搜索每一层,下面附上代码;
1.用二维向量存储的:
- #include <iostream>
- #include <bits/stdc++.h>
- #include <vector>
- using namespace std;
- const int N=150;
- int vex[N];//1已经访问,0,没有访问
- vector<int>a[N];
- void dfs(int x){//从x点开始
- if(vex[x]==1)return;
- vex[x]=1; //标记已经访问
- for(int i=0;i<a[x].size();i++){
- if(vex[a[x][i]]==0)dfs(a[x][i]); //如果未访问过就从当前点搜当前点能够到达的点(深搜)
- }
- }
- int main()
- {
- int n,m;
- cin>>n>>m;
- for(int i=0;i<m;i++){
- int x,y;
- cin>>x>>y;
- a[x].push_back(y);
- a[y].push_back(x);
- }
- int ans=0;
- for(int i=1;i<=n;i++){
- if(vex[i]==0){
- dfs(i);
- ans++;
- }
- }
- cout<<ans<<endl;
- }
2.用数组存储的:
- #include <bits/stdc++.h>
- #include <iostream>
- using namespace std;
- const int N=150;
- int vex[N];
- int mp[N][N];
- int n,m;
- void dfs(int x){
- if(vex[x]==1)return;
- vex[x]=1;
- for(int i=1;i<=n;i++){
- if(mp[x][i]!=0&&vex[mp[x][i]]==0)
- dfs(mp[x][i]);
- }
- }
- int main()
- {
- cin>>n>>m;
- for(int i=1;i<=n;i++){
- for(int j=1;j<=n;j++){
- mp[i][j]=0;
- }
- }
- for(int i=0;i<m;i++){
- int x,y;
- cin>>x>>y;
- mp[x][y]=y;
- mp[y][x]=x;
- }
- // for(int i=1;i<=n;i++){
- // for(int j=1;j<=n;j++){
- // cout<<mp[i][j];
- // }
- // cout<<endl;
- // }
- int ans=0;
- for(int i=1;i<=n;i++){
- if(vex[i]==0){
- ans++;
- dfs(i);
- }
- }
- cout<<ans<<endl;
- return 0;
- }
与AtCoder Beginner Contest 284的C题C - Ladder Takahashi 类似也是dfs深搜C - Ladder Takahashi (atcoder.jp)。标签:Count,AtCoder,Beginner,int,graph,vex,connected,dfs,mp From: https://www.cnblogs.com/saulgoodman1/p/17034881.html