Advertisement
Miha_Ch

ex_4.c

Apr 8th, 2025
576
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.15 KB | Software | 0 0
  1. #include <stdio.h>
  2.  
  3. #define MAX_PEOPLE 100000
  4.  
  5. int parent[MAX_PEOPLE + 1];
  6. int group_size[MAX_PEOPLE + 1];
  7.  
  8. void begin_group() {
  9.     for (int i = 1; i <= MAX_PEOPLE; i++) {
  10.         parent[i] = i;
  11.         group_size[i] = 1;
  12.     }
  13. }
  14.  
  15. int find_by_path_compression(int person_num) {
  16.     if (parent[person_num] != person_num) {
  17.         parent[person_num] = find_by_path_compression(parent[person_num]);
  18.     }
  19.     return parent[person_num];
  20. }
  21.  
  22. void groups_marger(int friend1, int friend2) {
  23.     int root_friend1 = find_by_path_compression(friend1);
  24.     int root_friend2 = find_by_path_compression(friend2);
  25.  
  26.     if (root_friend1 != root_friend2) {
  27.         if (group_size[root_friend1] < group_size[root_friend2]) {
  28.             parent[root_friend1] = root_friend2;
  29.             group_size[root_friend2] += group_size[root_friend1];
  30.         } else {
  31.             parent[root_friend2] = root_friend1;
  32.             group_size[root_friend1] += group_size[root_friend2];
  33.         }
  34.     }
  35. }
  36.  
  37. int get_friends_count(int x) {
  38.     int root = find_by_path_compression(x);
  39.     return group_size[root] - 1;
  40. }
  41.  
  42. int main() {
  43.     int N, M;
  44.  
  45.     printf("Enter number of people (N) and number of frienships (M): ");
  46.  
  47.     if (scanf("%d %d", &N, &M) != 2 || N <= 0 || N > MAX_PEOPLE || M < 0) {
  48.         printf("Invalid input.\n");
  49.         return 1;
  50.     }
  51.  
  52.     begin_group(); // Union Find
  53.  
  54.     printf("Please enter %d friendships. In every row: <person_num_1> <person_num_2>\n", M);
  55.  
  56.     for (int i = 0; i < M; i++) {
  57.         int a, b;
  58.         if (scanf("%d %d", &a, &b) != 2 || a < 1 || a > N || b < 1 || b > N) {
  59.             printf("invalid friendship number: %d %d\n", a, b);
  60.             continue;
  61.         }
  62.         groups_marger(a, b);
  63.     }
  64.  
  65.     int query;
  66.     while (scanf("%d", &query) != EOF) {
  67.         printf("Enter the number of the person for whom you want to see the number of friends (or nter 0 to exit): ");
  68.         if (query == 0) break;
  69.  
  70.         if (query < 1 || query > N) {
  71.             printf("Invalid person name: %d\n", query);
  72.         } else {
  73.             printf("%d\n", get_friends_count(query));
  74.         }
  75.     }
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement