1021. Deepest Root (25) @ PAT (Advanced Level) Practise
2013-08-25 11:23
471 查看
思路:
这题不难,主要就是深度优先搜索DFS算法。从每个点形如进行DFS,如果一次DFS后没有全部访问到,则用DFS0(简化版)遍历全部节点,并计算连通分量(components);如果全访问到了,记录maxDepth,并从下一个点开始继续DFS。
不过这题应该有什么优化方法吧,尽管没什么优化就AC了。
这题不难,主要就是深度优先搜索DFS算法。从每个点形如进行DFS,如果一次DFS后没有全部访问到,则用DFS0(简化版)遍历全部节点,并计算连通分量(components);如果全访问到了,记录maxDepth,并从下一个点开始继续DFS。
不过这题应该有什么优化方法吧,尽管没什么优化就AC了。
#include<iostream> #include<vector> #include<algorithm> using namespace std; int N; vector<vector<int>> G;//graph vector<bool> city;//visited vector<int > depth; int maxDepth; int components=1; void DFS(int i,int d) { if(d>maxDepth) maxDepth=d; d++; city[i]=true; vector<int>::iterator it; for(it=G[i].begin();it!=G[i].end();it++) { if(!city[*it]) { DFS(*it,d); } } d--; return ; } void DFS0(int i) { city[i]=true; vector<int>::iterator it; for(it=G[i].begin();it!=G[i].end();it++) { if(!city[*it]) { DFS0(*it); } } return; } int main() { cin>>N; city.resize(N); depth.resize(N); G.resize(N); int a,b; for(int i=0;i<N-1;i++) { cin>>a>>b; G[a-1].push_back(b-1); G[b-1].push_back(a-1); } for(int i=0;i<N;i++) { maxDepth=0; city.assign(N,false); DFS(i,0); while(true) { bool allVisited=true; int j=1; for(;j<city.size();j++) { if(city[j]==false) { allVisited=false; break; } } if(!allVisited) { components++; DFS0(j); } else { break; } } if(components!=1) { cout<<"Error: "<<components<<" components"; return 0; } depth[i]=maxDepth; } maxDepth=*max_element(depth.begin(),depth.end()); for(int i=0;i<N;i++) { if(depth[i]==maxDepth) { cout<<(i+1)<<endl; } } return 0; }
相关文章推荐
- PAT (Advanced Level) Practise 1021. Deepest Root (25)
- PAT (Advanced Level) Practise 1021 Deepest Root (25)
- PAT (Advanced Level) Practise 1021. Deepest Root (25)
- PAT (Advanced Level) Practise 1021 Deepest Root (25)
- PAT (Advanced Level)1021. Deepest Root (25)
- 浙大 PAT Advanced level 1021. Deepest Root (25)
- 【PAT Advanced Level】1021. Deepest Root (25)
- 【PAT】【Advanced Level】1021. Deepest Root (25)
- PAT (Advanced Level) Practise 1032 Sharing (25)
- PAT (Advanced Level) Practise 1052 Linked List Sorting (25)
- PAT (Advanced Level) Practise 1090 Highest Price in Supply Chain (25)
- 1013. Battle Over Cities (25)——PAT (Advanced Level) Practise
- PAT-PAT (Advanced Level) Practise 1006. Sign In and Sign Out (25) (简单题)【一星级】
- PAT (Advanced Level) Practise 1007. Maximum Subsequence Sum (25)
- PAT (Advanced Level) Practise 1003. Emergency (25) Dijstra扩展应用
- PAT (Advanced Level) Practise 1013. Battle Over Cities (25)
- PAT (Advanced Level) Practise 1126 Eulerian Path (25)
- PAT (Advanced Level) Practise 1118 Birds in Forest (25)
- PAT (Advanced Level) Practise 1109 Group Photo (25)
- PAT (Advanced Level) Practise - 1006. Sign In and Sign Out (25)