Graph

imnotleo

Leo

Posted on April 16, 2024

Graph

graph.hpp

#ifndef graph_hpp
#define graph_hpp

#include <iostream>
#include <cassert>
using namespace std;

class graph {

int n; // orden del grafo, cantidad de vertices
int m; // tamaño máximo del grafo, cantidad de aristas
//int s; // tamaño del grafo, cantidad de nodos

bool *T;

int f(int, int);

bool valid(int, int);

public:

graph(int);
~graph();

void set(int, int, bool = true); // vamos a quitar depende del get
bool get(int, int); // hay o no hay arista

int order() const { return n; }
//int size() const { return s; }

void print();
};


#endif /* graph_hpp */
Enter fullscreen mode Exit fullscreen mode

graph.cpp

#include "graph.hpp"

bool graph::valid(int i, int j){

  assert(0 < i and i <= n);
  assert(0 < j and j <= n);
  //assert(i != j);

  return true;
}

int graph::f(int i, int j) {

  valid(i,j);

  if (i < j) {
    int k = i;
    i = j;
    j = k;
  }

  return (i - 1) * (i - 2) / 2 + j - 1;
}


graph::graph(int ord): n(ord) {

  m = n * (n - 1) / 2;
  T = new bool[m];

  for (int i = 0; i < m; i++) T[i] = false;
}

graph::~graph() {

  delete [ ] T;
}

void graph::set(int i, int j, bool e) {

 valid(i,j);

  if (i != j) T[f(i,j)] = e;
}

bool graph::get(int i, int j) {

  valid(i,j);

  return i == j ? false : T[f(i,j)];
}

void graph::print() {

  for (int i = 1; i <= n; i++) {

    for (int j = 1; j <= n; j++) {

      if (i == j) cout << false << " ";
      else cout << T[f(i,j)] << " ";
    }
    cout << endl;
  }
}

Enter fullscreen mode Exit fullscreen mode

main.cpp

#include <iostream>
#include "graph.hpp"

int main() {

  graph G(6);

  G.set(1,3);
  G.set(1,6);
  G.set(2,3);
  G.set(2,5);
  G.set(2,4);
  G.set(3,5);
  G.set(4,5);
  G.set(4,6);
  G.set(5,6);

  G.print();
return 0;
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
imnotleo
Leo

Posted on April 16, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related