Exemplo n.º 1
0
void splay_tree()
{
    SplayTree<int> splayTree;
    
#define SPLAY_LOOP for (int i = 0; i < 20; i ++)

	SPLAY_LOOP
    {
        splayTree.Insert(i);
    }

	SPLAY_LOOP
    {
        assert(splayTree.Exists(i));
    }

	SPLAY_LOOP
    {
        splayTree.Delete(i);
    }

	SPLAY_LOOP
     {
         assert(!splayTree.Exists(i));
     }
}
Exemplo n.º 2
0
void dp()
{
	int i,j,k;
	ST st(start,0);
	tree.Insert(st);
	for (i=0;i<n;i++)
	{
		int lmin=maxl,rmin=maxl;
		SplayTree<ST>::node *p;
		while (1)
		{
			tree.Splay(tree.root,ST(a[i].l,0));
			p=tree.root;
			if (p==tree.nullnode||p->key>ST(a[i].r,0)) break;
			lmin=Min(lmin,Abs(p->key.key-a[i].l)+p->key.data);
			rmin=Min(rmin,Abs(a[i].r-p->key.key)+p->key.data);
			tree.Delete(p->key);
		}
		tree.Insert(ST(a[i].l,lmin));
		tree.Insert(ST(a[i].r,rmin));
	}
	int res=maxl;
	int tot=0;
	while (tree.root !=tree.nullnode)
	{
		tot++;
		res=Min(res,tree.root->key.data+Abs(tree.root->key.key));
		tree.Delete(tree.root->key);
	}	
	cout<<tot<<endl;
	printf("%d\n",res);
}
Node* LinkCutTree::_cutout(Node* vertex) {
    _liftUpToRoot(vertex);
    std::pair<SplayTree*, SplayTree*> splitedTrees = SplayTree::split(vertex->treePtr, Node::getSize(vertex->leftChild) + 1);
    SplayTree* right = splitedTrees.second;
    if(right->getRoot()) {
        right->find(0)->link = vertex;
    } else {
        delete right;
    }
    return vertex;
}
int main(int argn, char *argc[])
{
  int n = 1000;
  unsigned int t = time(0);
  int value;

  if (argn > 1)
    n = atoi(argc[1]);

  if (argn > 2)
    t = atoi(argc[2]);

  srand(t);

  cout << "testSplayTree " << n << " " << t << endl;

  SplayTree<int> tree;
  SplayTree<int>::Node *node;
  int i;

  cout << "Inserting " << n << " random values in treee ...\n";

  unsigned int insCount = 0, delCount = 0;

  for (i = 0; i < n; i++)
    {
      value = 1+(int) (n*100.0*rand()/(RAND_MAX+1.0));
      node = tree.search(value);
      if (node == NULL)
	{
	  insCount++;
	  node = new SplayTree<int>::Node (value);
	  tree.insert(node);
	}
    }

  cout << insCount << " Items inserted" << endl;

  for (i = 0; i < n; i++)
    {
      value = 1+(int) (n*100.0*rand()/(RAND_MAX+1.0));
      node = tree.remove(value);
      if (node != NULL)
	{
	  delCount++;
	  delete node;
	}
    }
    
  cout << delCount << " Items removed" << endl;

  destroyRec(tree.getRoot());
  cout << "testSplayTree " << n << " " << t << endl;
}
Exemplo n.º 5
0
void SplayNodeRefresh(SplayTree splay, Tree node)
{
  Compare cmp;

  AVERT(SplayTree, splay);
  AVERT(Tree, node);
  AVER(!SplayTreeIsEmpty(splay)); /* must contain node, at least */

  cmp = SplaySplay(splay, splay->nodeKey(node), splay->compare);
  AVER(cmp == CompareEQUAL);
  AVER(SplayTreeRoot(splay) == node);

  splay->updateNode(splay, node);
}
Exemplo n.º 6
0
int main(){
    SplayTree<int> tree;
    while(true){
        cout << "\n1 - dodaj wartosc\n";
        cout << "2 - znajdz wartosc\n";
        cout << "3 - usun wartosc\n";
        char c;
        cin >> c;
        if(c == '1'){
            cout << "Podaj wartosc: ";
            int i;
            cin >> i;
            tree.insert(i, i);
        }
        else if(c == '2'){
Exemplo n.º 7
0
int main()
{
	SplayTree T;
	while(1)
	{
		char c;
		cin >> c;
		if(c == 'i')
		{
			int i;
			cin >> i;
			T.insert(1,i);
			//T.print(T.root);
		}
		else
		{
Exemplo n.º 8
0
int main() {
    int command, id, key;
    while(scanf("%d", &command)) {
        if (!command) {
            break;
        } else if (command == 1) {
            scanf("%d%d", &id, &key);
            tree.insert(Client(id, key));
        } else if (command == 2) {
            printf("%d\n", tree.pop_max().id);
        } else if (command == 3) {
            printf("%d\n", tree.pop_min().id);
        }
    }
    return 0;
}
Exemplo n.º 9
0
Bool SplayFindFirst(Tree *nodeReturn, SplayTree splay,
                    SplayTestNodeFunction testNode,
                    SplayTestTreeFunction testTree,
                    void *closureP, Size closureS)
{
  SplayFindClosureStruct closureStruct;
  Bool found;

  AVER(nodeReturn != NULL);
  AVERT(SplayTree, splay);
  AVER(FUNCHECK(testNode));
  AVER(FUNCHECK(testTree));

  if (SplayTreeIsEmpty(splay) ||
      !testTree(splay, SplayTreeRoot(splay), closureP, closureS))
    return FALSE; /* no suitable nodes in tree */

  closureStruct.p = closureP;
  closureStruct.s = closureS;
  closureStruct.testNode = testNode;
  closureStruct.testTree = testTree;
  closureStruct.splay = splay;
  closureStruct.found = FALSE;

  found = SplaySplay(splay, &closureStruct,
                     SplayFindFirstCompare) == CompareEQUAL &&
          closureStruct.found;

  while (!found) {
    Tree oldRoot, newRoot;
    
    /* FIXME: Rename to "seen" and "not yet seen" or something. */
    oldRoot = SplayTreeRoot(splay);
    newRoot = TreeRight(oldRoot);

    if (newRoot == TreeEMPTY || !(*testTree)(splay, newRoot, closureP, closureS))
      return FALSE; /* no suitable nodes in the rest of the tree */
  
    /* Temporarily chop off the left half-tree, inclusive of root,
       so that the search excludes any nodes we've seen already. */
    SplayTreeSetRoot(splay, newRoot);
    TreeSetRight(oldRoot, TreeEMPTY);

    found = SplaySplay(splay, &closureStruct,
                       SplayFindFirstCompare) == CompareEQUAL &&
            closureStruct.found;

    /* Restore the left tree, then rotate left so that the node we
       just splayed is at the root.  Update both. */
    newRoot = SplayTreeRoot(splay);
    TreeSetRight(oldRoot, newRoot);
    SplayTreeSetRoot(splay, oldRoot);
    TreeRotateLeft(&splay->root);
    splay->updateNode(splay, oldRoot);
    splay->updateNode(splay, newRoot);
  }

  *nodeReturn = SplayTreeRoot(splay);
  return TRUE;
}
Exemplo n.º 10
0
void accept_tree(){
int n;
SplayTree st;
cout<<"Create splay tree: (enter 0 to finish)\n";
while(1) {
fflush(stdin);
cout<<"\nEnter node value: ";
cin>>n;
if(n==0) {
break;
}

root =st.Insert(n,root);
}
root = st.Delete(4, root);
}
Exemplo n.º 11
0
static Tree SplayTreeSuccessor(SplayTree splay)
{
  Tree oldRoot, newRoot;

  AVERT(SplayTree, splay);
  AVER(!SplayTreeIsEmpty(splay));

  oldRoot = SplayTreeRoot(splay);

  if (!TreeHasRight(oldRoot))
    return TreeEMPTY; /* No successor */

  /* temporarily chop off the left half-tree, inclusive of root */
  SplayTreeSetRoot(splay, TreeRight(oldRoot));
  TreeSetRight(oldRoot, TreeEMPTY);
  (void)SplaySplay(splay, NULL, compareLess);
  newRoot = SplayTreeRoot(splay);
  AVER(newRoot != TreeEMPTY);
  AVER(TreeLeft(newRoot) == TreeEMPTY);
  TreeSetLeft(newRoot, oldRoot);
  splay->updateNode(splay, oldRoot);
  splay->updateNode(splay, newRoot);

  return newRoot;
}
Exemplo n.º 12
0
void insertWithGrouping(SplayTree<string, Array<string> >& aSplayTree,
			string aArtist,
			string aMusicEntry)
{
    static int debug_count = 0;
    ostringstream os;
    os << "debug" << debug_count++ << ".dot";
    string filename = os.str();
 
    // Here aArtist is the key and aMusicEntry contributes toward the value
    BSTNode<string, Array<string> >* place = aSplayTree.findInsertionPoint(aArtist);
    if (place == nullptr) {
        // First node to be inserted
        Array<string> musicList;
        musicList.add(aMusicEntry);
        aSplayTree.setRoot(new BSTNode<string, Array<string> >(aArtist, musicList));
    } else if (aArtist == place->key()) {
        // Key matched
        // aArtist exists -- just group the current aMusicEntry with the existing
        // associated musicList
        Array<string> musicList = place->value();
        // Aggregation
        musicList.add(aMusicEntry);
        // Replace the value with the updated musicList
        place->setValue(musicList);
	// Splay this node as it is just augmented
	aSplayTree.splay(place);
    } else {
        // Key not matched
        // So, this is going to be the first music entry for aArtist
        Array<string> musicList;
        musicList.add(aMusicEntry);
        BSTNode<string, Array<string> >* newNode =
            new BSTNode<string, Array<string> >(aArtist, musicList,
                                                nullptr, nullptr, place);

        if (aArtist < place->key()) {
            // Node on the left of place
            place->setLeft(newNode);
        } else {
            // Node on the right of place
            place->setRight(newNode);
        }
	// dumpSplayTree(aSplayTree, filename);
        aSplayTree.splay(newNode);
    }
}
Exemplo n.º 13
0
void SplayNodeInit(SplayTree splay, Tree node)
{
  AVERT(SplayTree, splay);
  AVERT(Tree, node);
  AVER(!TreeHasLeft(node)); /* otherwise, call SplayNodeRefresh */
  AVER(!TreeHasRight(node)); /* otherwise, call SplayNodeRefresh */

  splay->updateNode(splay, node);
}
Exemplo n.º 14
0
Bool SplayFindLast(Tree *nodeReturn, SplayTree splay,
                   SplayTestNodeFunction testNode,
                   SplayTestTreeFunction testTree,
                   void *testClosure)
{
  SplayFindClosureStruct closureStruct;
  Bool found;

  AVER_CRITICAL(nodeReturn != NULL);
  AVERT_CRITICAL(SplayTree, splay);
  AVER_CRITICAL(FUNCHECK(testNode));
  AVER_CRITICAL(FUNCHECK(testTree));

  if (SplayTreeIsEmpty(splay) ||
      !testTree(splay, SplayTreeRoot(splay), testClosure))
    return FALSE; /* no suitable nodes in tree */

  closureStruct.testClosure = testClosure;
  closureStruct.testNode = testNode;
  closureStruct.testTree = testTree;
  closureStruct.splay = splay;

  found = SplaySplay(splay, &closureStruct,
                     SplayFindLastCompare) == CompareEQUAL &&
          closureStruct.found;

  while (!found) {
    Tree oldRoot, newRoot;
    
    oldRoot = SplayTreeRoot(splay);
    newRoot = TreeLeft(oldRoot);

    if (newRoot == TreeEMPTY || !(*testTree)(splay, newRoot, testClosure))
      return FALSE; /* no suitable nodes in the rest of the tree */
  
    /* Temporarily chop off the right half-tree, inclusive of root,
       so that the search excludes any nodes we've seen already. */
    SplayTreeSetRoot(splay, newRoot);
    TreeSetLeft(oldRoot, TreeEMPTY);

    found = SplaySplay(splay, &closureStruct,
                       SplayFindLastCompare) == CompareEQUAL &&
            closureStruct.found;

    /* Restore the right tree, then rotate right so that the node we
       just splayed is at the root.  Update both. */
    newRoot = SplayTreeRoot(splay);
    TreeSetLeft(oldRoot, newRoot);
    SplayTreeSetRoot(splay, oldRoot);
    TreeRotateRight(&splay->root);
    splay->updateNode(splay, oldRoot);
    splay->updateNode(splay, newRoot);
  }

  *nodeReturn = SplayTreeRoot(splay);
  return TRUE;
}
Exemplo n.º 15
0
void SplayDebugUpdate(SplayTree splay, Tree tree)
{
  AVERT(SplayTree, splay);
  AVERT(Tree, tree);
  if (tree == TreeEMPTY)
    return;
  SplayDebugUpdate(splay, TreeLeft(tree));
  SplayDebugUpdate(splay, TreeRight(tree));
  splay->updateNode(splay, tree);
}
Exemplo n.º 16
0
Bool SplayTreeInsert(SplayTree splay, Tree node)
{
  Tree neighbour;

  AVERT(SplayTree, splay);
  AVERT(Tree, node);
  AVER(TreeLeft(node) == TreeEMPTY);
  AVER(TreeRight(node) == TreeEMPTY);

  if (SplayTreeIsEmpty(splay)) {
    SplayTreeSetRoot(splay, node);
    return TRUE;
  }
  
  switch (SplaySplay(splay, splay->nodeKey(node), splay->compare)) {
  default:
    NOTREACHED;
    /* fall through */
  case CompareEQUAL: /* duplicate node */
    return FALSE;
    
  case CompareGREATER: /* left neighbour is at root */
    neighbour = SplayTreeRoot(splay);
    SplayTreeSetRoot(splay, node);
    TreeSetRight(node, TreeRight(neighbour));
    TreeSetLeft(node, neighbour);
    TreeSetRight(neighbour, TreeEMPTY);
    break;

  case CompareLESS: /* right neighbour is at root */
    neighbour = SplayTreeRoot(splay);
    SplayTreeSetRoot(splay, node);
    TreeSetLeft(node, TreeLeft(neighbour));
    TreeSetRight(node, neighbour);
    TreeSetLeft(neighbour, TreeEMPTY);
    break;
  }

  splay->updateNode(splay, neighbour);
  splay->updateNode(splay, node);
  return TRUE;
}
Exemplo n.º 17
0
void test_iterator(){
	MyAllocator allocator;
	allocator.constructor(1000);
	SplayTree<int,int> a;
	a.constructor(&allocator);
	SplayTreeIterator<int,int> b;
	b.constructor(&a);
	b.hasNext();
	b.hasNext();
	b.hasNext();
	b.next();
	a.insert(1);

	b.constructor(&a);
	b.hasNext();
	b.hasNext();
	b.hasNext();
	b.next();
	b.hasNext();
	b.hasNext();
}
Exemplo n.º 18
0
Bool SplayTreeDelete(SplayTree splay, Tree node)
{
  Tree leftLast;
  Compare cmp;

  AVERT(SplayTree, splay);
  AVERT(Tree, node);

  if (SplayTreeIsEmpty(splay))
    return FALSE;

  cmp = SplaySplay(splay, splay->nodeKey(node), splay->compare);
  AVER(cmp != CompareEQUAL || SplayTreeRoot(splay) == node);

  if (cmp != CompareEQUAL) {
    return FALSE;
  } else if (!TreeHasLeft(node)) {
    SplayTreeSetRoot(splay, TreeRight(node));
    TreeClearRight(node);
  } else if (!TreeHasRight(node)) {
    SplayTreeSetRoot(splay, TreeLeft(node));
    TreeClearLeft(node);
  } else {
    Tree rightHalf = TreeRight(node);
    TreeClearRight(node);
    SplayTreeSetRoot(splay, TreeLeft(node));
    TreeClearLeft(node);
    (void)SplaySplay(splay, NULL, compareGreater);
    leftLast = SplayTreeRoot(splay);
    AVER(leftLast != TreeEMPTY);
    AVER(!TreeHasRight(leftLast));
    TreeSetRight(leftLast, rightHalf);
    splay->updateNode(splay, leftLast);
  }

  TreeFinish(node);

  return TRUE;
}
Exemplo n.º 19
0
static Tree SplayUpdateRightSpine(SplayTree splay, Tree node, Tree child)
{
  AVERT_CRITICAL(SplayTree, splay);
  AVERT_CRITICAL(Tree, node);
  AVERT_CRITICAL(Tree, child);
  while (node != TreeEMPTY) {
    Tree parent = TreeRight(node);
    TreeSetRight(node, child); /* un-reverse pointer */
    splay->updateNode(splay, node);
    child = node;
    node = parent;
  }
  return child;
}
Exemplo n.º 20
0
int main() {
	int n, v;
	char cmd[32];
	while (scanf("%d", &n) != EOF) {
		SplayTree splay;
		for (int op = 0; op < n; ++op) {
			scanf("%s", cmd);
			if (!strcmp(cmd, "show")) {
				splay.show();
			} else if (!strcmp(cmd, "insert")) {
				scanf("%d", &v);
				splay.insert(v);
			} else if (!strcmp(cmd, "find")) {
				scanf("%d", &v);
				SplayTreeNode *ret = splay.find(v);
				printf("Find %d : %x\n", v, (unsigned)ret);
			} else if (!strcmp(cmd, "remove")) {
				scanf("%d", &v);
				splay.remove(v);
			}
		}
	}
	return 0;
}
Exemplo n.º 21
0
int main() {
  SplayTree st;
  vector<int> a;
  set<int> marked;
  int n = 7;

  for (int i = 0; i < n; ++i) {
    int t = rand() % n + 1;
    // remove duplicate elements.
    if (marked.count(t)) {
      --i;
      continue;
    }
    marked.insert(t);
    a.push_back(t);
  }
  for (int i = 0; i < n; ++i) {
    st.insert(a[i], true /*print*/);
  }
  for (int i = 0; i < n; ++i) {
    st.remove(a[i], true /*print*/);
  }
  return 0;
}
Exemplo n.º 22
0
static void SplayAssembleRev(SplayTree splay, SplayState state)
{
  Tree left, right;

  AVERT(SplayTree, splay);
  AVER(state->middle != TreeEMPTY);
  
  left = TreeLeft(state->middle);
  left = SplayUpdateRightSpine(splay, state->leftLast, left);
  TreeSetLeft(state->middle, left);

  right = TreeRight(state->middle);
  right = SplayUpdateLeftSpine(splay, state->rightFirst, right);
  TreeSetRight(state->middle, right);

  splay->updateNode(splay, state->middle);
}
Exemplo n.º 23
0
int main(){	
	long long int sum=0;
	int N;
	SplayTree<int> tr;
	scanf("%d",&N);
	for(int i=0;i<N;++i){
		int j;
		scanf("%d",&j);
		for(;j>0;--j){
			int n;
			scanf("%d",&n);
			tr.insert(n);
		}
		sum+=(tr.findMax()-tr.findMin());
		tr.remove(tr.findMax());
		tr.remove(tr.findMin());
	}
	cout<<sum<<endl;
}
Exemplo n.º 24
0
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  tree.init(n);
  while(m--) {
    int a, b;
    scanf("%d%d", &a, &b);
    Node* left = NULL, *right = NULL;
    if(a > 1) {
      split(tree.root, a-1, left, right);
    } else {
      right = tree.root;
    }

    //printf("left is \n");
    //debug(left);
    //printf("right is \n");
    //debug(right);
    Node* rleft = NULL, *rright = NULL;
    split(right, b - a + 1, rleft, rright);
    //printf("rleft is \n");
    //debug(rleft);
    //printf("rright is \n");
    //debug(rright);
    rleft->flip ^= 1;
    if(left != NULL)
      tree.root = merge(merge(left, rright), rleft);
    else if(rright != NULL)
      tree.root = merge(rright, rleft);
    else
      tree.root = rleft;
  }
  vector<int> v;
  traverse(tree.root, v);
  for(int i = 0; i < v.size(); i++)
    printf("%d\n", v[i]);
  return 0;
}
Exemplo n.º 25
0
int main(int argc, char const *argv[])
{
    while (scanf("%d", &n) != EOF)
    {
        Init();
        for (int i = 0; i < n; i++)
        {
            int v;
            scanf("%d", &v);
            pos[i] = newNode(v, nil);
        }
        for (int i = 0; i < n - 1; i++)
        {
            int u, v;
            scanf("%d%d", &u, &v);
            u--, v--;
            sp.Link(pos[u], pos[v]);
        }

//        scanf("%d", &m);
//        for (int i = 0; i < m; i++)
//        {
//            int typ, u, v, c;
//            scanf("%d%d%d", &typ, &u, &v);
//            u--, v--;
//            if (typ == 1)
//                printf("%d\n", sp.GetRoute(pos[u], pos[v])->maxsum);
//            else
//            {
//                scanf("%d", &c);
//                Node *p = sp.GetRoute(pos[u], pos[v]);
//                p->same = true;
//                p->sa = c;
//            }
//        }
    }
    return 0;
}
Exemplo n.º 26
0
int main(){
	MyAllocator allocator;
	allocator.constructor(1000);
	SplayTree<int,int> lol;
	lol.constructor(&allocator);
	srand(time(NULL));
	int n=10000000;
	int k=n;
	while(k--){
		lol.insert(k);
	}
	
	int i=0;
	SplayTreeIterator<int,int> iterator(&lol);
	while(iterator.hasNext()){
		SplayNode<int,int>*node=iterator.next();
		int v=node->getKey();
		i++;
	}

	lol.freeze();

	assert(i==n);
	assert(n==lol.size());
	SplayTreeIterator<int,int> iterator2(&lol);
	i=0;
	while(iterator2.hasNext()){
		SplayNode<int,int>*node=iterator2.next();
		int v=node->getKey();
		i++;
	}
	assert(i==n);
	assert(n==lol.size());

	test_remove();
	test_iterator();
	return 0;
}
Exemplo n.º 27
0
void test_remove(){
	MyAllocator allocator;
	allocator.constructor(1000);
	SplayTree<int,int> a;
	a.constructor(&allocator);
	for(int k=0;k<100;k++){
		a.insert(k);
		assert(a.find(k)!=NULL);
	}
	assert(a.size()==100);

	a.remove(9);
	assert(a.size()==99);
	assert(a.find(9)==NULL);

	a.remove(50);
	assert(a.size()==98);
	assert(a.find(50)==NULL);

	a.remove(50);
	assert(a.size()==98);
	assert(a.find(50)==NULL);

	a.remove(-1);

	assert(a.size()==98);
}
Exemplo n.º 28
0
int
main()
{
  SplayTree<SplayInt, SplayInt> tree;

  MOZ_RELEASE_ASSERT(tree.empty());

  MOZ_RELEASE_ASSERT(!tree.find(SplayInt(0)));

  static const int N = mozilla::ArrayLength(gValues);

  // Insert the values, and check each one is findable just after insertion.
  for (int i = 0; i < N; i++) {
    tree.insert(new SplayInt(gValues[i]));
    MOZ_RELEASE_ASSERT(tree.find(SplayInt(gValues[i])));
    tree.checkCoherency();
  }

  // Check they're all findable after all insertions.
  for (int i = 0; i < N; i++) {
    MOZ_RELEASE_ASSERT(tree.find(SplayInt(gValues[i])));
    tree.checkCoherency();
  }

  // Check that non-inserted values cannot be found.
  MOZ_RELEASE_ASSERT(!tree.find(SplayInt(-1)));
  MOZ_RELEASE_ASSERT(!tree.find(SplayInt(N)));
  MOZ_RELEASE_ASSERT(!tree.find(SplayInt(0x7fffffff)));

  // Remove the values, and check each one is not findable just after removal.
  for (int i = 0; i < N; i++) {
    SplayInt* removed = tree.remove(SplayInt(gValues[i]));
    MOZ_RELEASE_ASSERT(removed->mValue == gValues[i]);
    MOZ_RELEASE_ASSERT(!tree.find(*removed));
    delete removed;
    tree.checkCoherency();
  }

  MOZ_RELEASE_ASSERT(tree.empty());

  // Reinsert the values, in reverse order to last time.
  for (int i = 0; i < N; i++) {
    tree.insert(new SplayInt(gValues[N - i - 1]));
    tree.checkCoherency();
  }

  // Remove the minimum value repeatedly.
  for (int i = 0; i < N; i++) {
    SplayInt* removed = tree.removeMin();
    MOZ_RELEASE_ASSERT(removed->mValue == i);
    delete removed;
    tree.checkCoherency();
  }

  MOZ_RELEASE_ASSERT(tree.empty());

  return 0;
}
Exemplo n.º 29
0
static Compare SplaySplitRev(SplayStateStruct *stateReturn,
                             SplayTree splay, TreeKey key,
                             TreeCompareFunction compare)
{
  Tree middle, leftLast, rightFirst;
  Compare cmp;

  AVERT(SplayTree, splay);
  AVER(FUNCHECK(compare));
  AVER(!SplayTreeIsEmpty(splay));
  
  leftLast = TreeEMPTY;
  rightFirst = TreeEMPTY;
  middle = SplayTreeRoot(splay);
  for (;;) {
    cmp = compare(middle, key);
    switch(cmp) {
    default:
      NOTREACHED;
      /* defensive fall-through */
    case CompareEQUAL:
      goto stop;

    case CompareLESS:
      if (!TreeHasLeft(middle))
        goto stop;
      middle = SplayZigRev(middle, &rightFirst);
      cmp = compare(middle, key);
      switch(cmp) {
      default:
        NOTREACHED;
        /* defensive fall-through */
      case CompareEQUAL:
        goto stop;
      case CompareLESS:
        if (!TreeHasLeft(middle))
          goto stop;
        middle = SplayZigZigRev(middle, &rightFirst);
        splay->updateNode(splay, TreeRight(rightFirst));
        break;
      case CompareGREATER:
        if (!TreeHasRight(middle))
          goto stop;
        middle = SplayZagRev(middle, &leftLast);
        break;
      }
      break;

    case CompareGREATER:
      if (!TreeHasRight(middle))
        goto stop;
      middle = SplayZagRev(middle, &leftLast);
      cmp = compare(middle, key);
      switch(cmp) {
      default:
        NOTREACHED;
        /* defensive fall-through */
      case CompareEQUAL:
        goto stop;
      case CompareGREATER:
        if (!TreeHasRight(middle))
          goto stop;
        middle = SplayZagZagRev(middle, &leftLast);
        splay->updateNode(splay, TreeLeft(leftLast));
        break;
      case CompareLESS:
        if (!TreeHasLeft(middle))
          goto stop;
        middle = SplayZigRev(middle, &rightFirst);
        break;
      }
      break;
    }
  }

stop:
  stateReturn->middle = middle;
  stateReturn->leftLast = leftLast;
  stateReturn->rightFirst = rightFirst;
  return cmp;
}
Exemplo n.º 30
0
int main(int argc, char** argv)
{

    if (argc != 2) {
        cerr << "Provide the music file to process as an argument to the program." << endl;
        cerr << "Usage: " << argv[0] << " <filename>" << endl;
        exit(1);
    }
    
    // key --> artist name (string)
    // value --> Array of songs (array of strings)
    SplayTree<string, Array<string> > splayTree;
  
    ifstream ifs(argv[1]);
    string line;
    while(getline(ifs, line)) {
        string artist, musicEntry;
        processInput(line, artist, musicEntry);
        insertWithGrouping(splayTree, artist, musicEntry);
    }

    // Dump the initial splay tree
    dumpSplayTree(splayTree, "splay_tree0.dot");

    int count = 0;
    // Insertion into the splay tree is done
    // Now, let's go through the motions of inserting, deleting or finding
    while (true) {
        int input;
        ostringstream os;
        os << "splay_tree" << ++count << ".dot";
        string filename = os.str();
        cout << "Input choices:" << endl;
        cout << "* Insert (1)" << endl;
        cout << "* Find (2)" << endl;
        cout << "* Remove (3)" << endl;
        cout << "* Print sorted (4)" << endl;
        cout << "* Exit(0)" << endl;
        cin >> input;
        cin.ignore(256, '\n');
        switch(input) {
          case 1: {
              string artist, musicEntry;
              cout << "Artist: ";
              getline(cin, artist);
              cout << "Music: ";
              getline(cin, musicEntry);
              insertWithGrouping(splayTree, artist, musicEntry);
              dumpSplayTree(splayTree, filename);
              cout << "Done." << endl;
              break; 
          }
          case 2: {
              cout << "Find what (Enter artist name): ";
              string artist;
              getline(cin, artist);
              BSTNode<string, Array<string> >* approxMatchNode_lb = nullptr;
              BSTNode<string, Array<string> >* approxMatchNode_ub = nullptr;
              BSTNode<string, Array<string> >* node = 
                  splayTree.findApprox(artist, approxMatchNode_lb, approxMatchNode_ub);
              dumpSplayTree(splayTree, filename);
              if (node != nullptr) {
                  cout << "Accurately matched!" << endl;
              } else {
                  cout << "Approximate matches: " << endl;
                  if (approxMatchNode_lb) {
                      cout << "Artist: " << approxMatchNode_lb->key() << endl;
                      cout << "Songs: " << approxMatchNode_lb->value() << endl;
                  }
                  if (approxMatchNode_ub) {
                      cout << "Artist: " << approxMatchNode_ub->key() << endl;
                      cout << "Songs: " << approxMatchNode_ub->value() << endl;
                  }
              }
              break;
          }
          case 3: {
              cout << "Remove what (Enter artist name): ";
              string artist;
              getline(cin, artist);
              splayTree.remove(artist);
              dumpSplayTree(splayTree, filename);
              cout << "Done." << endl;
              break; 
          }
          case 4: {
              cout << "Sorted List: " << endl;
              splayTree.inorder();
              cout << "Done." << endl;
              break; 
          }
          case 0: {
              cout << "Exiting..." << endl;
              return 0;
          }
          default: {
              cout << "Invalid entry: Try again." << endl;
              break;
          }
        }
    }

    return 0;
}