题目地址:http://www.51cpc.com/web/problem.php?id=4260
Summarize:
1. 从图的角度来看就是求有无环;由于对图一窍不通,这里我用的是搜索;
2. 此外可以用并查集来做,是否存在多个根节点,若不止一个则不符合题意;
附搜索代码:
#include<iostream> #include<cstring> #define inf 1e9 typedef long long LL; using namespace std; const int N = 1e3+5; LL n, m, vis[N], edge[N][N], count, flag=0; void dfs(int x, int pre) { if(count == n) return; if(flag) return; for(int i=1; i<=n; i++) { if(edge[x][i] && x!=i && i!=pre) { if(vis[i]) { flag = 1; break; } vis[i] = 1; count++; dfs(i,x); } } } int main() { while(cin>>n>>m) { if(!n && !m) return 0; memset(vis, 0, sizeof(vis)); memset(edge, 0, sizeof(edge)); for(int a,b,i=0; i<m; i++) { cin>>a>>b; edge[a][b] = edge[b][a] = 1; } vis[1]=1; flag=0; count = 1; dfs(1, -1); if(count<n || flag) cout<<"No"<<endl; else cout<<"Yes"<<endl; } }