其实是自己没过去
理解了别人的代码
感觉自己都明白了自己改来改去就不对
也没地方问也没法改
就先理解好样例代码吧
复习set
自动去重
调用要设指针 (auto会报错)
#inclide <set>
set<int>::iterator it;
for(it = s.begin(); it != s.end(); it++)
printf("%d\n",*it);
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
int n, maxheight = 0;
vector<vector<int> > v;
bool visit[10010];
set<int> s;
vector<int> temp;
void dfs(int node, int height) {
if(height > maxheight) {
temp.clear();
temp.push_back(node);
maxheight = height;
} else if(height == maxheight){
temp.push_back(node);
}
visit[node] = true;
for(int i = 0; i < v[node].size(); i++) {
if(visit[v[node][i]] == false)
dfs(v[node][i], height + 1);
}
}
int main() {
scanf("%d", &n);
v.resize(n + 1);
int a, b, cnt = 0, s1 = 0;
for(int i = 0; i < n - 1; i++) {
scanf("%d%d", &a, &b);
v[a].push_back(b);
v[b].push_back(a);
}
for(int i = 1; i <= n; i++) {
if(visit[i] == false) {
dfs(i, 1);
if(i == 1) {
if (temp.size() != 0) s1 = temp[0];
for(int j = 0; j < temp.size(); j++)
s.insert(temp[j]);
}
cnt++;
}
}
if(cnt >= 2) {
printf("Error: %d components", cnt);
} else {
temp.clear();
maxheight = 0;
fill(visit, visit + 10010, false);
dfs(s1, 1);
for(int i = 0; i < temp.size(); i++)
s.insert(temp[i]);
set<int>::iterator it;
for(it = s.begin(); it != s.end(); it++)
printf("%d\n",*it);
}
return 0;
}
贴上自己没过的代码
求连通分量会了
加上自己理解的遍历树就不对了
应该是判断的地方有问题,,
#include <cstdio>
#include <iostream>
#include <set>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
int n, sum, maxheight;
int arr[11000][11000];
int brr[11000] = {0};
int crr[11000] = {0};
set<int> s;
vector<int> temp;
void lian(int i){
brr[i] = 1;
for(int j=1; j<n; j++){
if(arr[i][j]==1&&brr[j]==0)
lian(j);
}
}
/*void lian(int i, int height){
if(height>maxheight){
temp.clear();
temp.push_back(i);
maxheight = height;
}else if(height == maxheight){
temp.push_back(i);
}
brr[i] = 1;
for(int j=1; j<n; j++){
if(arr[i][j]==1&&brr[j]==0)
lian(j,height+1);
}
}*/
void dfs(int i, int height){
if(height>maxheight){
temp.clear();
temp.push_back(i);
maxheight = height;
}else if(height == maxheight){
temp.push_back(i);
}
crr[i] = 1;
for(int j=1; j<n; j++){
if(crr[j] == 0)
dfs(j,height+1);
}
}
int main(){
int a, b, s1;
scanf("%d",&n);
for(int i=1; i<n; i++){
scanf("%d%d",&a,&b);
arr[a][b] = arr[b][a] = 1;
}
for(int k=1; k<n; k++){
if(brr[k]==0){
lian(k);
/*if(k==1){
if(temp.size() != 0) s1 = temp[0];
for(int j=0; j<temp.size(); j++)
s.insert(temp[j]);
}*/
sum++;
}
}
if(sum >= 2 ){
printf("Error: %d components\n",sum);
}
else {
//dfs(a,1);
//int s1 = temp[0];
// for(int l=0; l<temp.size(); l++) s.insert(temp[l]);
for(int l=0; l<temp.size(); l++)
cout << temp[l] << "eeeeeeee" << endl;
temp.clear();
maxheight = 0;
memset(brr,0,sizeof(brr));
cout << s1 << "ssss" << endl;
dfs(s1,1);
for(int l=0; l<temp.size(); l++)
s.insert(temp[l]);
set<int>::iterator it;
for(it = s.begin(); it != s.end(); it++)
printf("%d\n",*it);
}
return 0;
}