PAT(甲级)1021笔记
1、原题参照PAT官网
2、生词
3、知识点
- set集合是c++ stl库中自带的一个容器,set具有以下两个特点:
- 1 set中的元素都是排好序的
- 2 set集合中没有重复的元素
- set、vector、iterator知识,关于set的基础知识以及vector ,set ,iterator的使用方法 set只能使用迭代器访问。
- vector :向量(Vector)是一个封装了动态大小数组的顺序容器(Sequence Container)。vector使用方法-菜鸟教程
- 然后,记得考虑输入节点为0的情况。
- 本题目主要考的双层DFS结构。
- 一个结论,即为从图中任意一个结点开始深度搜索,将高度最高的一个或几个结点记录下来,再从这几个结点中的任意一个结点开始深度搜索,再把高度最大的一个或几个结点记录下来,对这两个结点的集合求并集即为我们所求的深度最大的树的根节点。
- 求连通分量无非就是求对这个图进行深度搜索的时候一共调用了几次深度优先搜索函数,如果图是连通的则调用一次深度优先搜索函数就可完成对图的搜索,若不是连通图则需调用多次,调用的次数即为连通分量数。
- 哈哈代码更正过一次,要注意MAXSIZE是10的四次方哦、太小的话2、3测试点过不去,会显示数组越界~
4、代码record
#include<stdio.h>
#include<string>
#include<queue#include<stdio.h>
#include<string>
#include<queue>
#include<stack>
#include<iostream>
#include<vector>
#include <iomanip>
#include<set>
using namespace std;
#define MAXSIZE 10000
int N;
vector<int>GraphT[MAXSIZE];
bool vis[MAXSIZE] = { false };
int maxdepth = 0;
set<int> deepestroots;
void DFS(int u, int depth) {
if (maxdepth<depth)
{
maxdepth = depth;
deepestroots.clear();
deepestroots.insert(u + 1);
}
else if(maxdepth==depth)
{
deepestroots.insert(u + 1);
}
vis[u] = true;
for (int j = 0; j < GraphT[u].size(); j++)
{
int t = GraphT[u][j];
if (!vis[t]) {
DFS(t, depth + 1);
}
}
}
void DFSTrave(vector<int>* GraphT)
{
int count = 0;
for (int i = 0; i < N; i++) {
if (!vis[i]) {
DFS(i, 1);
count++;
}
}
if (count == 1) {
set<int>::iterator it = deepestroots.begin();
int s = *(it)-1;
maxdepth = 0;
fill(vis, vis + MAXSIZE, false);
set<int>deepestroots_temp = deepestroots;
deepestroots.clear();
DFS(s, 1);
it = deepestroots_temp.begin();
for (it; it != deepestroots_temp.end(); it++)
{
deepestroots.insert(*it);
}
it = deepestroots.begin();
for (it; it != deepestroots.end(); it++) {
cout << *(it) <<endl;
}
}
else {
cout << "Error: " << count << " components" << endl;
}
}
int main() {
cin >> N;
if (N==1)
{
cout << "1" << endl;
return 0;
}
for (int i = 0; i < (N-1); i++)
{
int a, b;
cin >> a >> b;
GraphT[a - 1].push_back(b - 1);
GraphT[b - 1].push_back(a - 1);
}
DFSTrave(GraphT);
return 0;
}