fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node* link;
  5. typedef struct node
  6. {
  7. int num; //연결된 노드 번호
  8. link next; //연결리스트 구현을 위한 포인터
  9. } node;
  10.  
  11. link *arr, *visit; //arr = 연결리스트, visit = 방문여부
  12. int ans = 0; //제출 정답
  13.  
  14. link createN(link head, int a) //연결리스트 생성 함수
  15. {
  16. link c = head, temp = NULL;
  17.  
  18. temp = (link)malloc(sizeof(node));
  19.  
  20. temp->num = a;
  21. temp->next = NULL;
  22.  
  23. if (!head)
  24. {
  25. head = temp;
  26.  
  27. return head;
  28. }
  29.  
  30. while (c->next) c = c->next;
  31.  
  32. c->next = temp;
  33.  
  34. return head;
  35. }
  36.  
  37. void go(link head) //탐색 함수(특 : 재귀)
  38. {
  39. while (head)
  40. {
  41. if (!visit[head->num])
  42. {
  43. ans++;
  44. visit[head->num] = 1; //방문 여부 온(on이라는 뜻 ㅎ)
  45. go(arr[head->num]);
  46. }
  47.  
  48. head = head->next;
  49. }
  50. }
  51.  
  52. int main()
  53. {
  54. int i, cnt, cnum, tmp1, tmp2;
  55.  
  56. scanf("%d", &cnum);
  57.  
  58. arr = (link)malloc(sizeof(node) * (cnum + 1)); //숫자 안 헷갈리기 위한 몸부림
  59. visit = (int*)calloc(cnum + 1, sizeof(int));
  60.  
  61. for (i = 1; i <= cnum; i++) arr[i] = NULL; //초기화
  62.  
  63. scanf("%d", &cnt);
  64.  
  65. for (i = 0; i < cnt; i++)
  66. {
  67. scanf("%d %d", &tmp1, &tmp2);
  68.  
  69. arr[tmp1] = createN(arr[tmp1], tmp2); //양방향 생성을 위해 서로 쏴주기
  70. arr[tmp2] = createN(arr[tmp2], tmp1); //양방향 생성을 위해 서로 쏴주기
  71. }
  72.  
  73. visit[1] = 1;
  74. go(arr[1]);
  75.  
  76. printf("%d\n", ans);
  77.  
  78. return 0;
  79. }
Success #stdin #stdout 0s 9424KB
stdin
7
6
1 2
2 3
1 5
5 2
5 6
4 7
stdout
2