1.题面
You are given an unweighted, undirected graph. Write a program to check if it’s a tree topology.
Input
The first line of the input file contains two integers N and M — number of nodes and number of edges in the graph (0 < N <= 10000, 0 <= M <= 20000). Next M lines contain M edges of that graph — Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).
Output
Print YES if the given graph is a tree, otherwise print NO.
Example
Input:
3 2
1 2
2 3Output:
YES
2.思路
- 根据树的定义 e=n-1的连通图 故可将题目转换为图的连通性问题。对于新手我来说,问题分解为:
- 如何存储图,使用vector实现邻接表
- 如何判断图的的连通性,采取DFS
3.代码
#include <iostream>
#include <vector>
using namespace std;
int check[10000 + 5];
int n, m;
int counter = 0;
void dfs(vector<int> *node,int i) {
if (!node[i].size()) return;
check[i]++;
counter++;
for (int k = 0; k < node[i].size(); k++) {
int temp = node[i][k];
if(!check[temp])dfs(node,temp);
}
}
int main() {
while (cin >> n >> m) {
int u, v;
vector<int> node[10000 + 5];
for (int i = 0; i < m; i++) {
cin >> u >> v;
node[u].push_back(v);
node[v].push_back(u);
}
if (m != n - 1) { cout << "NO" << endl; continue; }
dfs(node,1);
if (counter != n) cout << "NO" << endl;
else cout << "YES" << endl;
counter = 0;
for (int i = 0; i < n+1; i++)
check[i] = 0;
}
return 0;
}
4.所得
图的存储有这样几种可能:
一种简明的链表前向插入构造:
struct Edge{
int to,next;
};
Edge E[1010];
int head[110],Ecou;
void init() {
memset(head,-1,sizeof(head));
Ecou=0;
}
void addEdge(int u,int v) {
E[Ecou].to=v;
E[Ecou].next=head[u];
head[u]=Ecou++;
}
- 图的连通性:
- 利用非递归DFS再做一遍此题
- 使用Union Find再做一遍此题