囉囉嗦嗦寫在前面的話:
這學期有算法分析與設計課,每週的作業是在Vjudge上刷相應的題目,爲了方便以後回顧我就把代碼搬到這裏來了 。也希望能幫助其他刷題的朋友,代碼不要完完全全複製粘貼(強調強調),重要的是看思路,不懂的大家可以一起交流!米娜桑,一起加油哇!
翠花兒,上題!
Given an undirected graph G which has N vertice and M edges, determine whether G is a tree.
Input
The first line contains an integer T, the number of test cases. (1 ≤ T ≤ 10) For each test case the first line contains 2 integers N and M. (2 ≤ N ≤ 500, 1 ≤ M ≤ 100000)
The following M lines each contain 2 integers a and b representing that there is an edge between a and b. (1 ≤ a, b ≤ N)
Output
For each test case output "YES" or "NO" indicating whether G is a tree or not.
Sample Input
2 3 2 3 1 3 2 5 5 3 1 3 2 4 5 1 2 4 1
Sample Output
YES NO
思路:
首先,自由樹是一個連通且無環的無向圖。在判斷連通性時我是用深度優先搜索進行判斷的,無環我使用了|E| =|V|-1 來判斷的。
在構建圖的時候我自己寫了一個鏈表,後來覺得這樣做很傻 - - 明明有vector可以用,何樂而不爲呢?
代碼如下:
#include <iostream>
//自由樹是一個連通/無環的無向圖
#include <queue>
#define MAX 501
using namespace std;
struct ArcNode //邊表節點
{
int adjvex;
ArcNode* next;
};
struct VertexNode //頂點表節點
{
int vertex;
ArcNode* firstedge;
};
class AdjGraph //鄰接鏈表表示圖
{
private:
VertexNode adjlist[MAX];//存放頂點的數組
int vertexNum, arcNum;//圖的頂點數和邊數
int visited[MAX]; //用來判斷頂點是否被訪問過
public:
AdjGraph(int n, int m);//構造函數 n個頂點 m條邊
void Insert (int a, int b);
void DFS(int v); //深度優先搜索
bool validTree();
void show();//顯示鄰接鏈表構造 測試用
};
AdjGraph::AdjGraph(int n, int m)
{
vertexNum = n;
arcNum = m;
for(int i = 0; i < vertexNum ;i++)
{
visited[i] = 0;
adjlist[i].vertex = i+1;//頂點是從1開始的
adjlist[i].firstedge = NULL;
}
}
void AdjGraph::Insert(int a, int b)
{
ArcNode *pArc = new ArcNode();
pArc->adjvex = b;
if(adjlist[a-1].firstedge == NULL)
{
adjlist[a-1].firstedge = pArc;
}
else
{
ArcNode *p = adjlist[a-1].firstedge;
while(p->next!=NULL)
{
p = p->next;
}
p->next = pArc;
} //接下來重複對 b->a
ArcNode *fpArc = new ArcNode();
fpArc->adjvex = a;
if(adjlist[b-1].firstedge == NULL)
{
adjlist[b-1].firstedge = fpArc;
}
else
{
ArcNode *p = adjlist[b-1].firstedge;
while(p->next!=NULL)
{
p = p->next;
}
p->next = fpArc;
}
}
void AdjGraph:: DFS(int v)
{
visited[v-1] = 1;
ArcNode *p = adjlist[v-1].firstedge;
while(p!=NULL)
{
int j = p->adjvex;
if(visited[j-1]==0)
DFS(j);
p = p->next;
}
}
void AdjGraph:: show()
{
cout<<"鄰接鏈表: "<<endl;
for(int i =0; i < vertexNum ; i++)
{
cout << adjlist[i].vertex;
ArcNode *p = adjlist[i].firstedge;
while (p != NULL)
{
cout<< "-> "<<p->adjvex;
p = p->next;
}
cout<< " ->NULL"<<endl;
}
}
bool AdjGraph::validTree()
{
//證明圖無環用|E|=|V|-1
if (arcNum !=(vertexNum -1))
return false;
//證明圖是連通的
DFS(1);
for(int i =0; i < vertexNum; i++)
{
if (visited[i]==0)
return false;
}
return true;
}
int main()
{
int T=0;
cin>>T;
for (int i = 0; i < T; i++)
{
int N=0;
int M=0;
cin>>N>>M;
AdjGraph myGraph(N,M);
for(int j = 0; j < M ;j++)
{
int a,b;
cin>>a>>b;
myGraph.Insert(a,b);
}
//myGraph.show();
if(myGraph.validTree()) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
/*AdjGraph myGraph(3,2);
myGraph.Insert(3,1);
myGraph.Insert(3,2);
myGraph.show();
*/
return 0;
}