Created
October 30, 2013 00:43
-
-
Save RomarioTeles/7225327 to your computer and use it in GitHub Desktop.
Programa feito para somar com a nota da primeira avaliações parciais 1 e 2 de Algoritmo e Estruturas de dados 2 - Arvore de busca binaria e grafos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.LinkedList; | |
import java.util.Queue; | |
import java.util.Scanner; | |
public class ep1 { | |
//cria a 'Estrutura' de um nó | |
private static Scanner entrada; | |
private static class NO { | |
public int info; | |
public NO dir, esq; | |
}//fim NO | |
// operações de inserção, busca e remoção | |
//inicio abb_Inserir | |
public static NO abb_Inserir(NO r, int chave) { | |
if (r == null) { | |
r = new NO(); | |
r.info = chave; | |
r.esq = null; | |
r.dir = null; | |
} else if (chave <= r.info) { | |
r.esq = abb_Inserir(r.esq, chave); | |
} else | |
r.dir = abb_Inserir(r.dir, chave); | |
return r; | |
}// fim abb_Inserir | |
//inicio abb_consultar | |
public static int abb_Consultar(NO r, int chave, int busca) { | |
// caso o nó existir na arvore o metodo retornara busca = 1 | |
if (r != null && busca == 0) { | |
if (r.info == chave) | |
busca = 1; | |
else if (chave < r.info) { | |
busca = abb_Consultar(r.esq, chave, busca); | |
} else { | |
busca = abb_Consultar(r.dir, chave, busca); | |
} | |
} | |
return busca; | |
}//fim abb_consultar | |
//inicio abb_MostrarEmOrdem | |
public static void abb_MostrarEmOrdem(NO r) { | |
if (r != null) { | |
abb_MostrarEmOrdem(r.esq); | |
System.out.print(r.info + " "); | |
abb_MostrarEmOrdem(r.dir); | |
} | |
}//fim abb_MostrarEmOrdem | |
public static void abb_MostrarEmPreOrdem(NO r) { | |
if (r != null) { | |
System.out.print(r.info + " "); | |
abb_MostrarEmPreOrdem(r.esq); | |
abb_MostrarEmPreOrdem(r.dir); | |
} | |
} | |
//inicio abb_MostrarEmPosOrdem | |
public static void abb_MostrarEmPosOrdem(NO r) { | |
if (r != null) { | |
abb_MostrarEmPosOrdem(r.esq); | |
abb_MostrarEmPosOrdem(r.dir); | |
System.out.print(r.info + " "); | |
} | |
}//Fim abb_MostrarEmPosOrdem | |
//inicio abb_MostrarEmLargura | |
public static void abb_MostrarEmLargura(NO raiz) { | |
Queue<NO> queue = new LinkedList<NO>(); | |
if (raiz == null) | |
return; | |
queue.clear(); | |
queue.add(raiz); | |
while (!queue.isEmpty()) { | |
NO aux = queue.remove(); | |
System.out.print(aux.info + " "); | |
if (aux.esq != null) | |
queue.add(aux.esq); | |
if (aux.dir != null) | |
queue.add(aux.dir); | |
} | |
}//fim abb_MostrarEmLargura | |
//inicio abb_Remove | |
public static NO abb_Remove(NO r, int chave) { | |
if (r == null) | |
return null; | |
else if (r.info > chave) {// o programa desviara o sentido para a | |
// subarvore a esquerda | |
r.esq = abb_Remove(r.esq, chave); | |
} else if (r.info < chave) {// o programa desviara o sentido para a | |
// subarvore a direita | |
r.dir = abb_Remove(r.dir, chave); | |
} else { | |
if (r.esq == null && r.dir == null) { // o no não possui filhos | |
r = null; | |
} else if (r.esq == null) { // o no possui somente um filho, | |
// subarvore a direita | |
r = r.dir; | |
} else if (r.dir == null) {// o no possui apenas um filho, subarvore | |
// a esquerda | |
r = r.esq; | |
} else { // o no tem filhos em ambos os lados | |
NO aux = r.esq; | |
while (aux.dir != null) { | |
aux = aux.dir; | |
} | |
r.info = aux.info; | |
aux.info = chave; | |
r.esq = abb_Remove(r.esq, chave); | |
} | |
} | |
return r; | |
}//fim abb_Remove | |
// menu de opçoes | |
//inicio opcaoInserir | |
public static NO opcaoInserir(NO raiz) { | |
System.out.print("Digite o numero a ser inserido: "); | |
int chave = entrada.nextInt(); | |
raiz = abb_Inserir(raiz, chave); | |
System.out.println("Numero inserido!"); | |
System.out.print("ESTADO DA ARVORE: \nEm Ordem: "); | |
abb_MostrarEmOrdem(raiz); | |
System.out.print("\nEm Pré-Ordem: "); | |
abb_MostrarEmPreOrdem(raiz); | |
System.out.print("\nEm Pós-Ordem: "); | |
abb_MostrarEmPosOrdem(raiz); | |
System.out.print("\nEm Largura: "); | |
abb_MostrarEmLargura(raiz); | |
return raiz; | |
} // fim opcaoInserir | |
//inicio opcaoRemover | |
public static NO opcaoRemover(NO raiz) { | |
if (raiz == null) | |
System.out.println("Árvore vazia!"); | |
else { | |
System.out.println("\nEstado da arvore: "); | |
abb_MostrarEmOrdem(raiz); | |
System.out.print("\nDigite o número a ser removido: "); | |
int chave = entrada.nextInt(); | |
int busca = 0; | |
busca = abb_Consultar(raiz, chave, busca); | |
if (busca == 0) | |
System.out.println("Numero não encontrado na árvore!"); | |
else { | |
raiz = abb_Remove(raiz, chave); | |
System.out.println("Número removido da árvore!"); | |
System.out.print("ESTADO DA ARVORE:\nEm Ordem: "); | |
abb_MostrarEmOrdem(raiz); | |
System.out.print("\nEm Pré-Ordem: "); | |
abb_MostrarEmPreOrdem(raiz); | |
System.out.print("\nEm Pós-Ordem: "); | |
abb_MostrarEmPosOrdem(raiz); | |
System.out.print("\nEm Largura: "); | |
abb_MostrarEmLargura(raiz); | |
} | |
} | |
return raiz; | |
}// fim opcao remover | |
public static void opcaoEstatistica(NO raiz) { | |
if (raiz == null) | |
System.out.println("Árvore vazia!"); | |
else { | |
System.out.println("ESTADO DA ARVORE:"); | |
System.out.println("\nNº de nós: " + abb_quantidadeDeNos(raiz)); | |
System.out.println("Minimo: " + abb_Minimo(raiz)); | |
System.out.println("Maximo: " + abb_Maximo(raiz)); | |
System.out.println("Altura: " + abb_Altura(raiz)); | |
} | |
}// fim estatisticas | |
// fim menu de opcoes | |
// fim Operações de inserção, busca e remoção | |
// -------------------------------------------------------------- | |
// funcionalidades do menu Estatisticas : altura, maximo, minimo e | |
// quantidades de nós | |
// -------------------------------------------------------------- | |
// este metodo retorna a altura da arvore | |
public static int abb_Altura(NO r) { | |
int altura_esq = 0, altura_dir = 0, altura = 0; | |
while (r != null) { | |
altura_esq = abb_Altura(r.esq); | |
altura_dir = abb_Altura(r.dir); | |
if (altura_dir > altura_esq) { | |
altura = altura_dir + 1; | |
return altura; | |
} else { | |
altura = altura_esq + 1; | |
return altura; | |
} | |
} | |
return altura; | |
}//fim abb_Altura | |
// este metodo retorna o numero total de nos | |
public static int abb_quantidadeDeNos(NO r) { | |
int numeroDeNos = 0; | |
while (r != null) { | |
numeroDeNos = abb_quantidadeDeNos(r.esq) | |
+ abb_quantidadeDeNos(r.dir) + 1; | |
return numeroDeNos; | |
} | |
return numeroDeNos; | |
}// fim abb_quantidadeDeNos | |
// este metodo retorna o menor valor da arvore | |
public static int abb_Minimo(NO r) { | |
while (r.esq != null) { | |
r = r.esq; | |
} | |
return r.info; | |
}//fim abb_Minimo | |
// este metodo retorna o maior valor da arvore | |
public static int abb_Maximo(NO r) { | |
while (r.dir != null) { | |
r = r.dir; | |
} | |
return r.info; | |
} // fim abb_maximo | |
//fim Estatisticas | |
public static void main(String[] args) { | |
entrada = new Scanner(System.in); | |
NO raiz = null; | |
char opcao;// armazena a opção | |
do { | |
System.out | |
.println("\n MENU DE OPÇÕES\n " | |
+ "_______________________________________________________\n"); | |
System.out.print("|I| - Inserir na árvore. "); | |
System.out.println("|R| - Remover nó. "); | |
System.out.print("|E|- Estatisticas "); | |
System.out.println(" |S| - Sair e Esvaziar árvore"); | |
System.out.print("DIGITE A OPÇÃO: "); | |
opcao = ((entrada.next()).toUpperCase()).charAt(0); | |
System.out | |
.println("________________________________________________________"); | |
switch (opcao) { | |
case 'I': | |
raiz = opcaoInserir(raiz); | |
break; | |
case 'E': | |
opcaoEstatistica(raiz); | |
break; | |
case 'R': | |
raiz = opcaoRemover(raiz); | |
break; | |
case 'S': | |
if (raiz == null) { | |
System.out.println("Arvore Vazia!"); | |
} else { | |
raiz = null; | |
System.out.println("Arvore esvaziada!"); | |
} | |
break; | |
default: | |
System.out.println("Opção Inválida!"); | |
} | |
} while (opcao != 'S'); | |
} // fim main | |
} // fim classe ep1 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.util.HashSet; | |
import java.util.Scanner; | |
import java.util.TreeSet; | |
import java.util.Vector; | |
/* VOCÊ ESTÁ NA CLASSE EP2.JAVA */ | |
public class Ep2 { | |
static TreeSet<Aresta> arestas = new TreeSet<Aresta>(); | |
Kruskal aresta_grafo = new Kruskal(); | |
/* VOCÊ ESTÁ NA CLASSE ARESTA.JAVA */ | |
class Aresta implements Comparable<Aresta> { | |
int vert1, vert2; | |
int custo; | |
public Aresta(int primeiro_vertice, int vertice_adjavente, int custo) { | |
this.vert1 = primeiro_vertice; | |
this.vert2 = vertice_adjavente; | |
this.custo = custo; | |
} | |
public int getPrimeiro_vertice() { | |
return vert1; | |
} | |
public int getVertice_adjacente() { | |
return vert2; | |
} | |
@Override | |
public String toString() { | |
return "(" + vert1 + ", " + vert2 + "): " + custo; | |
} | |
public int compareTo(Aresta aresta) { | |
return (this.custo < aresta.custo) ? -1 : 1; | |
} | |
public int getCusto() { | |
return custo; | |
} | |
} | |
/* VOCÊ ESTÁ NA CLASSE KRUSKAl.JAVA */ | |
class Kruskal { | |
Vector<HashSet<Integer>> vertices = new Vector<HashSet<Integer>>(); | |
TreeSet<Aresta> arestas = new TreeSet<Aresta>(); | |
public TreeSet<Aresta> getArestas() { | |
return arestas; | |
} | |
HashSet<Integer> getPar_de_vertices(int vertice1) { | |
for (HashSet<Integer> par_de_vertices : vertices) { | |
if (par_de_vertices.contains(vertice1)) { | |
return par_de_vertices; | |
} | |
} | |
return null; | |
} | |
public void inserirArestas(Aresta aresta) { | |
int v = aresta.getPrimeiro_vertice(); | |
int w = aresta.getVertice_adjacente(); | |
HashSet<Integer> colecao_vertice_v = getPar_de_vertices(v); | |
HashSet<Integer> colecao_vertice_w = getPar_de_vertices(w); | |
if (colecao_vertice_v == null) { | |
arestas.add(aresta); | |
if (colecao_vertice_w == null) { | |
HashSet<Integer> novo_vertice = new HashSet<Integer>(); | |
novo_vertice.add(v); | |
novo_vertice.add(w); | |
vertices.add(novo_vertice); | |
} else { | |
colecao_vertice_w.add(v); | |
} | |
} else { | |
if (colecao_vertice_w == null) { | |
colecao_vertice_v.add(w); | |
arestas.add(aresta); | |
} else if (colecao_vertice_v != colecao_vertice_w) { | |
colecao_vertice_v.addAll(colecao_vertice_w); | |
vertices.remove(colecao_vertice_w); | |
arestas.add(aresta); | |
} | |
} | |
} | |
} | |
/* VOCÊ ESTÁ NO METODO INSEREARESTAS DA CLASSE EP2.JAVA */ | |
public void InsereArestas(String caminho) throws FileNotFoundException { | |
Scanner arquivo = new Scanner(new File(caminho)); | |
int num_vertices = arquivo.nextInt(); | |
int num_arestas = arquivo.nextInt(); | |
for (int i = 0; i < num_arestas; i++) { | |
int vert_u = arquivo.nextInt(); | |
int vert_v = arquivo.nextInt(); | |
int c = arquivo.nextInt(); | |
arestas.add(new Aresta(vert_u, vert_v, c)); | |
} | |
} | |
/* VOCÊ ESTÁ NO METODO MOSTRAGRAFO DA CLASSE EP2.JAVA */ | |
public void mostraGrafo() { | |
System.out | |
.println("__________________________________________\n\n::::::::::Representação do grafo:::::::::"); | |
System.out.println("Legenda: (vertice, v. Adjacente) : custo\n "); | |
for (Aresta aresta : arestas) { | |
System.out.println(aresta); | |
aresta_grafo.inserirArestas(aresta); | |
} | |
} | |
/* VOCÊ ESTÁ NO METODO CAMINHOMINIMO DA CLASSE EP2.JAVA */ | |
public void caminhoMinimo() { | |
System.out | |
.println("__________________________________________\n\nÁrvore Geradora Mínima:\n"); | |
int total = 0; | |
for (Aresta aresta : aresta_grafo.getArestas()) { | |
System.out.println(aresta); | |
total += aresta.getCusto(); | |
} | |
System.out.println("Custo mínimo: " + total | |
+ "\n__________________________________________"); | |
} | |
/* VOCÊ ESTÁ NO METODO MAIN DA CLASSE EP2.JAVA */ | |
public static void main(String[] args) throws FileNotFoundException { | |
Scanner Entrada = new Scanner(System.in); | |
System.out.print("Entre com o caminho do arquivo: "); | |
String caminho = Entrada.next(); | |
Ep2 ep2 = new Ep2(); | |
ep2.InsereArestas(caminho); | |
ep2.mostraGrafo(); | |
ep2.caminhoMinimo(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment