【发布时间】:2014-08-11 00:32:05
【问题描述】:
我正在尝试解决一个 SPOJ 问题is it a tree ?,在该问题中我必须检查一个图是否是树? 在这个问题中,我使用 DFS 来检测图形是否有循环..
我的代码是..
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <string.h>
using namespace std;
typedef long long int64;
typedef unsigned long long uint64;
#define two(X) (1<<(X))
#define twoL(X) (((int64)(1))<<(X))
#define contain(S,X) (((S)&two(X))!=0)
#define containL(S,X) (((S)&twoL(X))!=0)
const double pi=acos(-1.0);
const double eps=1e-11;
template<class T> inline void checkmin(T &a,T b){if(b<a) a=b;}
template<class T> inline void checkmax(T &a,T b){if(b>a) a=b;}
template<class T> inline T sqr(T x){return x*x;}
typedef pair<int,int> ipair;
#define SIZE(A) ((int)A.size())
#define LENGTH(A) ((int)A.length())
#define MP(A,B) make_pair(A,B)
#define PB(X) push_back(X)
int scanInt()
{
char c;
int ans=0;
while(true)
{
c=getchar_unlocked();
if(c==' ' || c=='\n')
return ans;
ans=(ans<<3)+(ans<<1)+c-'0';
}
}
bool applyDFS(vector<vector<int> > &graph,int n)
{
queue <int> st;
int i,j=0;
vector<bool> visited(n+1,false);
int node=1;
st.push(1);
while(!st.empty())
{
node=st.front();
st.pop();
if(visited[node])
{
return false;
}
visited[node]=true;
for(i=0;i<graph[node].size();i++)
{
if(!visited[graph[node][i]])
st.push(graph[node][i]);
}
j++;
}
return j==n?true:false;
}
int main()
{
int n,m,x,y,i;
//freopen("input.txt","r",stdin);
n=scanInt();
m=scanInt();
vector <vector<int> > graph(n+1);
stack <int > st;
for(i=0;i<m;i++)
{
x=scanInt();
y=scanInt();
graph[x].PB(y);
graph[y].PB(x);
st.push(x);
}
if(applyDFS(graph,n))
cout<<"YES\n";
else
cout<<"NO\n";
return 0;
}
当我提交解决方案时,我收到“超出时间限制”消息。有没有更好的方法来解决这个问题??
【问题讨论】:
-
您无需尝试寻找周期。想想一棵树的属性,最重要的是,它有多少个组件?它有多少条边?
-
@kevmo314 你可以有一个包含 3 个节点和 2 条边的图,它不是一棵树(它包含一个循环)。所以这绝对是一个“如果”,而不是“仅当”
-
@alfasin 您的图表有两个组件。
-
@alfasin 好吧,我想避免直接给出答案,但是树是具有一个组件和 V-1 边的图。参见:en.wikipedia.org/wiki/Tree_(graph_theory),即“G 是连通的并且有 n-1 条边。”
-
@kevmo314 再次正确,但是,森林(树木的集合)也是一个图。因此,如果要严格一点,就不能避免检查周期和连通性。
标签: algorithm graph depth-first-search