- Codice:
#include <fstream>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <string.h>
using namespace std;
struct nodo
{
int value;
string percors;
nodo *left;
nodo *right;
};
bool verificatree (vector < nodo > &inp)
{
nodo *root = NULL, *cur = NULL, *prev = NULL;
for (vector < nodo >::iterator it = inp.begin (); it != inp.end (); it++)
{
nodo n = *it;
if (n.percors.size () == 0)
{
if (root != NULL)
{
return false;
}
else
{
root = &(*it);
}
}
else
{
cur = root;
for (string::iterator pit = n.percors.begin (); pit != n.percors.end (); pit++)
{
if (cur == NULL)
return false;
prev = cur;
if (*pit == 'S')
cur = cur->left;
else if (*pit == 'D')
cur = cur->right;
}
if (cur != NULL)
return false;
if (n.percors[n.percors.size () - 1] == 'S')
prev->left = &(*it);
else if (n.percors[n.percors.size () - 1] == 'D')
prev->right = &(*it);
}
}
return true;
}
bool findpercors(nodo *root, vector<int> &percors, int k)
{
if (root == NULL) return false;
percors.push_back(root->value);
if (root->value == k)
return true;
if ( (root->left && findpercors(root->left, percors, k)) ||
(root->right && findpercors(root->right, percors, k)) )
return true;
percors.pop_back();
return false;
}
int findLCA(nodo *root, int n1, int n2)
{
vector<int> percors1, percors2;
if ( !findpercors(root, percors1, n1) || !findpercors(root, percors2, n2))
return -1;
int i;
for (i = 0; i < percors1.size() && i < percors2.size() ; i++)
if (percors1[i] != percors2[i])
break;
return percors1[i-1];
}
int main (void)
{
ifstream in("in.txt");
ofstream out("out.txt");
int pr1, pr2;
in >> pr1>>pr2;
char nodo_data[1000];
char temp[100];
vector < nodo > inp;
while (in >> nodo_data)
{
if (nodo_data[0] == '(' && nodo_data[1] == ')')
{
if (verificatree (inp))
{
vector < nodo >::iterator it = inp.begin ();
out << findLCA( &(*(inp.begin ())) , pr1, pr2);
}
else
out << "Albero non valido";
out << endl;
inp.clear ();
continue;
}
nodo n;
sscanf (nodo_data, "(%d,%s)", &n.value, temp);
temp[strlen (temp) - 1] = '\0';
n.percors = temp;
n.left = n.right = NULL;
vector < nodo >::iterator it;
for (it = inp.begin (); inp.size () > 0 && it != inp.end (); it++)
{
if ((*it).percors.length () > n.percors.length () || ((*it).percors.length () == n.percors.length () && (*it).percors > n.percors))
{
inp.insert (it, n);
break;
}
}
if (inp.size () == 0 || it == inp.end ())
inp.push_back (n);
}
return 0;
}
- Codice:
3 4
(2,S) (4,SS) (6,DS) (7,DD) (3,D) (5,SD) (1,) ()
(1,S) (4,SS) (6,DS) (7,DD) (3,D) (5,SD) (2,) ()
(3,L) (4,R) ()
(2,S) (4,SS) (6,DS) (7,DD) (3,D) (5,SD) (1,) ()
(2,S) (4,SS) (6,DS) (3,D) (1,) ()
- Codice:
1
2
Albero non valido
1
1