fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. #define faster ios_base::sync_with_stdio(false);cin.tie(NULL); cout.tie(NULL);
  5. int n, m;
  6. const int N = 1005;
  7. vector<int> adj[N];
  8. bool visited[N];
  9. vector<int> largest_component;
  10.  
  11. void inp() {
  12. cin >> n >> m;
  13. for(int i = 1; i <= m; i++) {
  14. int x, y; cin >> x >> y;
  15. adj[x].push_back(y);
  16. adj[y].push_back(x);
  17. }
  18. }
  19.  
  20. int dfs(int u, vector<int> &component) {
  21. int cnt = 1;
  22. component.push_back(u);
  23. visited[u] = true;
  24. for(auto v : adj[u]) {
  25. if(!visited[v]) {
  26. cnt += dfs(v, component);
  27. }
  28. }
  29. return cnt;
  30. }
  31.  
  32. void ntkt() {
  33. memset(visited, false, sizeof(visited));
  34. int max_size = 0;
  35.  
  36. for(int i = 1; i <= n; i++) {
  37. if(!visited[i]) {
  38. vector<int> tmp_path;
  39. int size = dfs(i, tmp_path);
  40. if(size > max_size) {
  41. max_size = size;
  42. largest_component = tmp_path;
  43. }
  44. }
  45. }
  46.  
  47. cout << max_size << "\n";
  48. for(auto x : largest_component) cout << x << " ";
  49. cout << "\n";
  50. }
  51.  
  52. int main() {
  53. faster;
  54. inp();
  55. ntkt();
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 5268KB
stdin
12 7
1 2
2 5
2 6
6 10
3 4
9 11
9 12
stdout
5
1 2 5 6 10