Advertisement
Guest User

Untitled

a guest
May 6th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int vertices;
  5. int edgesCount;
  6. int *edges;
  7.  
  8. #define getIndex(x, y) ((vertices) * (y) + (x))
  9. #define getEl(x, y) (edges + getIndex((x), (y)))
  10. #define getVal(x ,y) (*getEl((x), (y)))
  11.  
  12. void readMatrix(FILE *file) {
  13. fscanf(file, "%d\n", &vertices);
  14. edges = calloc((size_t) vertices * vertices, sizeof(int));
  15. edgesCount = 0;
  16.  
  17. int first, second;
  18. while(-1 != fscanf(file, "%d %d\n", &first, &second)) {
  19. int *el = getEl(first, second);
  20. if (!*el) {
  21. *el = 1;
  22. getVal(second, first) = 1;
  23. ++edgesCount;
  24. }
  25. }
  26.  
  27. return ;
  28. }
  29.  
  30. int search(int *elements, int size, int what) {
  31. int i;
  32. for (i = 0; i < size; ++i) {
  33. if (what == elements[i]) {
  34. return i;
  35. }
  36. }
  37. return -1;
  38. }
  39.  
  40. int checkCoherence(int excluded) {
  41. int visited[vertices];
  42. int i;
  43. for (i = 0; i < vertices; ++i) {
  44. visited[i] = 0;
  45. }
  46. visited[excluded] = 1;
  47. int stack[vertices * 2];
  48. stack[0] = visited[0] ? 1 : 0;
  49. int SP = 1;
  50.  
  51. while (SP > 0) {
  52. int vertice = stack[--SP];
  53. int vToAdd;
  54. for (vToAdd = 0; vToAdd < vertices; ++vToAdd) {
  55. if (!getVal(vToAdd, vertice)) continue;
  56. if (-1 != search(stack, SP, vToAdd)) continue;
  57. if (visited[vToAdd]) continue;
  58. stack[SP++] = vToAdd;
  59. }
  60. visited[vertice] = 1;
  61. }
  62.  
  63. for (i = 0; i < vertices; ++i) {
  64. if (!visited[i]) {
  65. return 0;
  66. }
  67. }
  68.  
  69. return 1;
  70. }
  71.  
  72. int checkTree(int excluded) {
  73. int excludedEdges = 0;
  74. int x;
  75. for (x = 0; x < vertices; ++x) {
  76. if (getVal(x, excluded)) ++excludedEdges;
  77. }
  78. return (edgesCount - excludedEdges + 1) == (vertices - 1);
  79. }
  80.  
  81. int main() {
  82. FILE *file = fopen("input.txt", "rt");
  83.  
  84. if (!file) {
  85. printf("Создайте файл `input.txt` такого формата:\n"
  86. "```\n"
  87. "Кол-во_вершин\n"
  88. "Вершина1 Вершина2\n"
  89. "...\n"
  90. "БЕЗ переноса строки в конце```\n");
  91. }
  92.  
  93. readMatrix(file);
  94.  
  95. int excluded;
  96. for (excluded = 0; excluded < vertices; ++excluded) {
  97. printf("Vertice: %d\n", excluded);
  98. printf(" Coherence: %i\n", checkCoherence(excluded));
  99. printf(" Tree: %i\n", checkTree(excluded));
  100. if (checkCoherence(excluded) && checkTree(excluded)) {
  101. printf("FIND! VERTICE: %d\n", excluded);
  102. }
  103. }
  104.  
  105. return 0;
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement