summaryrefslogtreecommitdiff
path: root/sem_5/HLIN501_Graphes/TP/TP1/tp1.cc
blob: 414a003bfd1381f7db0144b8149698f7e74f32e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <cstdlib>
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

void ecritureTailles(int n, int m, int comp[]);
void composantes(int n, int m, int edge[][2], int comp[]);
void grapheRandom(int,int, int[][2]);
void printgraphe (int, int, int[][2]);

int main(int argc, char ** argv)
{
  int n;     // Nombre de sommets.
  int m;     // Nombre d'aretes.
  cout << "Entrer le nombre de sommets:";
  cin >> n;
  cout << "Entrer le nombre d'aretes:";
  cin >> m;
  int edge[m][2];    // Tableau des aretes.
  int comp[n];       // comp[i] est le numero de la composante contenant i.
  grapheRandom(n,m,edge);
  //printgraphe(n,m,edge);
  composantes(n,m,edge,comp);
  cout<<endl<<endl;
  ecritureTailles(n,m,comp);

  return EXIT_SUCCESS;
}

void ecritureTailles(int n, int m, int comp[]){
  int comptemp[n];
  int compteur = 0;
  int tab[n];//n sera le nombre de cellule dans la composante, t[n] sera le nombre de composantes de tant de cellules
  for(int i =0 ; i <n; i ++){
    comptemp[i]=0;
    tab[i]=0;
  }
  for (int i = 0 ; i < n; i ++){
    if (comptemp[comp[i]]==0) compteur ++;
    comptemp[comp[i]] ++; //comptemp est a present un tableau qui pour n numero d'une composante associe le nombre de cellule incluses
  }
  for (int i =0; i < n; i ++){
    tab[comptemp[i]-1]++;
  }

  cout<<"Il y a "<<compteur<<" composantes connexes"<<endl;
  cout<<"Lesquelles sont : "<< endl;
  for (int i = 0 ; i<n; i ++){
    if (tab[i]>=1){
      cout<<"Il y a "<< tab[i] << " composantes de taille "<< i+1 << " Sommets"<<endl;
    }
  }
}
void composantes(int n, int m, int edge[][2], int comp[]){
  int taille[n];
  vector<int> L[n];
  for (int i = 0 ; i < n; i ++) {
    comp[i]=i;
    taille[i]=1;
    L[i].push_back(i);
  }
  for ( int i = 0 ; i < m; i ++){
    int * x = &comp[edge[i][0]];
    int * y = &comp[edge[i][1]];
    if (*x != *y){
      if (taille[*x]>taille[*y]){
        swap(x,y);
      }
      int aux = *x;
      taille[*y]+=taille[aux];
      for(int j = 0; j < taille[aux]; j ++){
        int tmp = L[aux].back();
        comp[tmp]=*y;
        L[*y].push_back(tmp);
        L[aux].pop_back();
      }
    }
  }
}

void printgraphe (int n, int m, int edge[][2]){
  cout<<n<<" Sommets et "<<m<<" aretes"<<endl;
  for (int i = 0 ; i < m; i ++){
    cout << "Arete "<< i << ":[" <<edge[i][0]<< ";"<<edge[i][1]<<"]";
  }
  cout<<endl;
}

void grapheRandom(int n,int m, int edge[][2]){
  srand(time(NULL));
  for (int i = 0; i < m;i ++){
    edge[i][0]=rand()%n;
    edge[i][1]=rand()%n;
  }
}