dbtype_t bonsai_insert(pgctx_t *ctx, dbtype_t node, dbtype_t key, dbtype_t value, int insert_or_fail) { int cmp; dbval_t *np; if (!node.all) { return bonsai_new(ctx, DBNULL, DBNULL, key, value); } np = dbptr(ctx, node); cmp = dbcmp(ctx, key, np->key); if (insert_or_fail && cmp==0) { node.type = Error; return node; } if (cmp < 0) { return balance(ctx, node, bonsai_insert(ctx, np->left, key, value, insert_or_fail), np->right, subtree_left, 1); } if (cmp > 0) { return balance(ctx, node, np->left, bonsai_insert(ctx, np->right, key, value, insert_or_fail), subtree_right, 1); } np->value = value; return node; }
static dbtype_t _bonsai_delete(pgctx_t *ctx, dbtype_t node, dbtype_t key, dbtype_t *valout) { dbval_t *np = dbptr(ctx, node); dbtype_t min, left, right; int cmp; if (!node.all) { if (valout) valout->type = Error; return DBNULL; } left = np->left; right = np->right; cmp = dbcmp(ctx, key, np->key); if (cmp < 0) { return balance(ctx, node, _bonsai_delete(ctx, left, key, valout), right, subtree_left, 1); } if (cmp > 0) { return balance(ctx, node, left, _bonsai_delete(ctx, right, key, valout), subtree_right, 1); } if (valout) *valout = np->value; rcuwinner(node, 0xe9); if (!left.all) return right; if (!right.all) return left; right = delete_min(ctx, right, &min); return balance(ctx, min, left, right, subtree_right, 0); }
//continues the insert of the avl void AVLTreeIndex::insert(AVL_Node*& root, Term* value) { //if root = null than it will create the new alphabetical avl tree if (root == NULL){ root = new AVL_Node; root->left = NULL; root->right = NULL; root->data = value; return; } //if the roots word is greater than the word in value insert left and than balance else if (value->get_name() < root->data->get_name()){ insert(root->left, value); root = balance(root); } //if the roots word is less than the word in value insert right and than balance else if (value->get_name() > root->data->get_name()){ insert(root->right, value); root = balance(root); } //if the roots word is equal to the word in value than it will just return else if(value->get_name() == root->data->get_name() == 0 ){ return; } //return root; }
Tree * balance (Tree * tree) { if (tree -> nil) return tree; Balance balanced = balanceCase(tree); switch (balanced) { case Balanced: tree -> left = balance(tree -> left); tree -> right = balance(tree -> right); return tree; case LL: ll++; tree -> left = balance(tree -> left); tree -> right = balance(tree -> right); return rotateLL(tree); case LR: lr++; tree -> left = balance(tree -> left); tree -> right = balance(tree -> right); return rotateLR(tree); case RL: rl++; tree -> left = balance(tree -> left); tree -> right = balance(tree -> right); return rotateRL(tree); case RR: rr++; tree -> left = balance(tree -> left); tree -> right = balance(tree -> right); return rotateRR(tree); } }
void RedBlackTree::insert(string k, int v){ if(_root == NULL) { _root = new Node(k,v); _root->setisRed(false); } else { Node* actual = _root; bool continua = true; while(continua) { int comparison=cmp(actual->getKey(),k); if(comparison >= 0) { // ---------------- LEFT case ------------------------------ if(actual->getLeft() == NULL) { //había espacio Node* nuevo = new Node(k,v); nuevo->setFather(actual); actual->setLeft(nuevo); //no se si debería ser balance nuevo o actual if( actual->isRed() ) balance(nuevo); continua = false; break; } else actual = actual->getLeft(); } else { // -------------------- RIGHT case ------------------------- if(actual->getRight() == NULL) { Node* nuevo = new Node(k,v); nuevo->setFather(actual); actual->setRight(nuevo); if( actual->isRed() ) balance(nuevo); continua = false; break; } else actual = actual->getRight(); } }//end of while(continua) }//end of else [case tree is not empty] }
int main(int argc, char *argv[]) { balance("CONSUBSTANTIATION"); balance("WRONGHEADED"); balance("UNINTELLIGIBILITY"); balance("SUPERGLUE"); return 0; }
avlnode * Tree::insertion(avlnode * temp, int value, int value1) { avlnode * temp1 = findnode(value); if (temp1!=NULL) { ((temp1->head2)->head)=(temp1->head2)->add(value1); return temp; } if (temp==NULL) { temp = new avlnode; temp->data=value; temp->left=NULL; temp->right=NULL; temp->head2=new Connection; ((temp->head2)->head)=(temp->head2)->add(value1); } else if (value>temp->data) { temp->left=insertion(temp->left, value, value1); temp=balance (temp); } else if (value<temp->data) { temp->right=insertion(temp->right, value, value1); temp=balance (temp); } return temp; }
int balance(TreeNode* root, int& res) { if (!root) return 0; int left_balance = balance(root->left, res); int right_balance = balance(root->right, res); int left_flow = abs(left_balance); int right_flow = abs(right_balance); res += left_flow + right_flow; return root->val - 1 + left_balance + right_balance; }
static void balance(char **data, int len) { if (len) { int n = (len + 1) / 2; char **p = data + n - 1; printf("%s\n", *p); balance(data, n - 1); balance(p + 1, len - n); } }
static TLDNode *addnode(TLDList *tld, char *hostname, TLDNode *node) { if(node == NULL) { TLDNode *node = (TLDNode *)malloc(sizeof(TLDNode)); if(node != NULL) { node->parent = NULL; node->content = hostname; node->left = NULL; node->right = NULL; node->count = 1; tld->root = node; tld->size++; } else { free(node); } return node; }else{ int cmp = strcmp(hostname, node->content); if(cmp < 0) { if (node->left != NULL) //turn left return addnode(tld, hostname, node->left); //recursive else { //add node if blank TLDNode *n = makeNode(hostname); n->parent = node; node->left = n; balance(node->left); //create the balance } } else if(cmp > 0) { if (node->right != NULL) return addnode(tld, hostname, node->right); else { TLDNode *n = makeNode(hostname); n->parent = node; node->right = n; balance(node->right); } } else { free(hostname); node->count++; } } return node; }
/*---------------------------------------------------------------------------- * stack_update - goes up stack readjusting balance as needed. This function * serves as a testiment to the philosophy of commenting while you code, 'cos * hell if I can remember how I got to this. I think is has something to do * with the varying effects on tree height, depending on exactly which sub * tree, or sub-sub tree was modified. TODO study and comment *--------------------------------------------------------------------------*/ static void stack_update(RUMAVL *tree, RUMAVL_STACK *stack, signed char diff) { RUMAVL_STACK *tmpstack; /* if diff becomes 0, we quit, because no further change to ancestors * can be made */ while (stack != NULL && diff != 0){ signed char ob, nb; ob = (*stack->node)->balance; (*stack->node)->balance += diff * (signed char)stack->dir; nb = (*stack->node)->balance; if (diff < 0){ if (stack->dir == -1 && ob < 0){ if (nb > 0) nb = 0; diff = (nb - ob) * -1; }else if (stack->dir == 1 && ob > 0){ if (nb < 0) nb = 0; diff = nb - ob; }else{ diff = 0; } }else{ if (stack->dir == -1 && nb < 0){ if (ob > 0) ob = 0; diff = (nb - ob) * -1; }else if (stack->dir == 1 && nb > 0){ if (ob < 0) ob = 0; diff = nb - ob; }else{ diff = 0; } } while ((*stack->node)->balance > 1){ diff += balance(stack->node, -1); } while ((*stack->node)->balance < -1){ diff += balance(stack->node, 1); } tmpstack = stack; stack = stack->next; mem_free(tree, tmpstack); } /* we may exit early if diff becomes 0. We still need to free all stack * entries */ while (stack != NULL){ tmpstack = stack; stack = stack->next; mem_free(tree, tmpstack); } }
//- Remove the data member's entry in the tree. Returns CUBIT_TRUE //- if item removed, CUBIT_FALSE if item not in tree. template <class Z> CubitBoolean KDDTree<Z>::remove (Z data) { //// If the Add List is not empty, action must be taken if (myAddList.size() > 0) { if (mySelfBalancingOn == CUBIT_TRUE) // self-balancing is on, so rebalance the tree { balance (); } else // self-balancing is off, so put everything in the Add List onto the tree { dump_list (); } } //// Tree is empty if (root == NULL) { return CUBIT_FALSE; } //// Tree is not empty else { KDDTreeNode<Z> *P = find_node_containing_data (root, data); if (P == NULL) // no matching node was found { return CUBIT_FALSE; } else // mark the matching node for deletion { if (P->valid == CUBIT_FALSE) { return CUBIT_FALSE; // this node was already deleted } P->valid = CUBIT_FALSE; // set the node to be deleted myMarkedNodes++; if (myDeletionTolerance != 0) { if ( (( static_cast<double>(myMarkedNodes) / myNodeList.size()) > myDeletionTolerance) && (myMarkedNodes > 1) ) { balance (); } } return CUBIT_TRUE; } } }
int out(int &money, int a) { if (money >= a) { money -= a; balance(money); return 0; } else { printf("Error,¾lÃB¤£¨¬\n"); balance(money); return 0; } }
//how to judge a tree is balanced binary tree bool balance(TreeNode* root, TreeNode* leftp, TreeNode* rightp) { if(root == NULL) return true; int left = depth(root->leftp); int right = depth(root->rightp); int diff = left - right; if(diff > 1 || diff < -1) { return false; } return balance(root->leftp) && balance(root->rightp); }
static dbtype_t _bonsai_multi_delete(pgctx_t *ctx, dbtype_t node, dbtype_t key, dbtype_t *value) { dbval_t *np = dbptr(ctx, node); dbtype_t min, left, right; int cmp; int i; if (!node.all) { value->type = Error; return DBNULL; } left = np->left; right = np->right; cmp = dbcmp(ctx, key, np->key); if (cmp < 0) { return balance(ctx, node, _bonsai_delete(ctx, left, key, value), right, subtree_left, 1); } if (cmp > 0) { return balance(ctx, node, left, _bonsai_delete(ctx, right, key, value), subtree_right, 1); } if (np->nvalue == 1) { if (dbcmp(ctx, *value, np->values[0])!=0) { value->type = Error; return node; } if (!left.all) return right; if (!right.all) return left; right = delete_min(ctx, right, &min); rcuwinner(node, 0xe9); return balance(ctx, min, left, right, subtree_right, 0); } node = bonsai_copy(ctx, left, right, node); np = dbptr(ctx, node); for(i=0; i<np->nvalue; i++) { if (dbcmp(ctx, *value, np->values[i])==0) { memcpy(np->values+i, np->values+i+1, (np->nvalue-i-1)*sizeof(dbtype_t)); break; } } if (i == np->nvalue) { value->type = Error; } else { np->nvalue--; } return node; }
void balance(tree *t) { if(t==NULL) return ; if(t!=NULL) { printf("\n Balance factor of node %d is %d",t->data,height(t->left)-height(t->right)); if(t->left) balance(t->left); if(t->right) balance(t->right); return; } end; }
MyMoneyMoney PivotCell::cellBalance(const MyMoneyMoney& _balance) { MyMoneyMoney balance(_balance); balance += *this; balance = (balance * m_stockSplit) + m_postSplit; return balance; }
static int _insertavl(Avl **tp, Avl *p, Avl *r, int (*cmp)(Avl*,Avl*), Avl **rfree) { int i, ob; if(*tp == nil){ r->bal = 0; r->n[0] = nil; r->n[1] = nil; r->p = p; *tp = r; return 1; } ob = (*tp)->bal; if((i=canoncmp(cmp(r, *tp))) != 0){ (*tp)->bal += i*_insertavl(&(*tp)->n[(i+1)/2], *tp, r, cmp, rfree); balance(tp, p); return ob==0 && (*tp)->bal != 0; } /* install new entry */ *rfree = *tp; /* save old node for freeing */ *tp = r; /* insert new node */ **tp = **rfree; /* copy old node's Avl contents */ if(r->n[0]) /* fix node's children's parent pointers */ r->n[0]->p = r; if(r->n[1]) r->n[1]->p = r; return 0; }
static struct node* insert(struct node* n, const void* k, int (*cmp)(const void*, const void*), struct node** found) { struct node* r; int c; if (!n) { n = malloc(sizeof *n); if (n) { n->key = k; n->left = n->right = 0; n->height = 1; } *found = n; return n; } c = cmp(k, n->key); if (c == 0) { *found = n; return 0; } r = insert(c < 0 ? n->left : n->right, k, cmp, found); if (r) { if (c < 0) n->left = r; else n->right = r; r = balance(n); } return r; }
struct node* insert(struct node* root, int value) { if(root == NULL){ return newnode(value); } if(value < root->data){ root->left = insert(root->left, value); } else { root->right = insert(root->right, value); } root->height = compare(heightof(root->left), heightof(root->right)) + 1; b = balance(root); if(b > 1){ if(value < root->left->data){ //left left return rightrotate(root); } else { //left right root->left = leftrotate(root->left); return rightrotate(root); } } if(b < -1){ if(value > root->right->data){ //right right return leftrotate(root); } else { //right left root->right = rightrotate(root->right); return leftrotate(root); } } return root; }
void setq(const Char *name, Char **vec, struct varent *p, int flags) { struct varent *c; int f; f = 0; /* tree hangs off the header's left link */ while ((c = p->v_link[f]) != 0) { if ((f = *name - *c->v_name) == 0 && (f = Strcmp(name, c->v_name)) == 0) { if (c->v_flags & VAR_READONLY) stderror(ERR_READONLY|ERR_NAME, c->v_name); blkfree(c->vec); c->v_flags = flags; trim(c->vec = vec); return; } p = c; f = f > 0; } p->v_link[f] = c = xmalloc(sizeof(struct varent)); c->v_name = Strsave(name); c->v_flags = flags; c->v_bal = 0; c->v_left = c->v_right = 0; c->v_parent = p; balance(p, f, 0); trim(c->vec = vec); }
QDomElement Pad::getDom(QDomDocument& doc) { QDomElement dom_elem = doc.createElement("pad"); dom_elem.setAttribute("active", isActive()); dom_elem.setAttribute("volume", volumePercent()); dom_elem.setAttribute("balance", balance()); return dom_elem; }
static Node* insert(ElemType &&elem, Node* &t, const comparator_type &less) { Node *ret = nullptr; if (t == nullptr) { t = new Node(gtl::move(elem)); ret = t; } else if (less(elem, t->elem)) { if (t->left) ret = insert(gtl::move(elem), t->left, less); else { t->left = new Node(gtl::move(elem), t); ret = t->left; } } else if (less(t->elem, elem)) { if (t->right) ret = insert(gtl::move(elem), t->right, less); else { t->right = new Node(gtl::move(elem), t); ret = t->right; } } else { ret = t; } balance(t); return ret; }
BigInt *add(BigInt *a, BigInt *b) { int size = MAX(a->size, b->size) + 5; int longer = MAX(a->length, b->length); int shorter = MIN(a->length, b->length); BigInt *bigger; if (longer==a->length) { bigger = a; } else { bigger = b; } int length = longer; int *digits = (int*)malloc(size*sizeof(int)); int i; for(i=0;i<length;i++) { if(i>=shorter) { digits[i]=bigger->digits[i]*bigger->sign; } else { digits[i] = a->digits[i]*a->sign + b->digits[i]*b->sign; } } BigInt *result = (BigInt*)malloc(sizeof(BigInt)); result->sign = 1; result->size = size; result->length = length; result->digits = digits; result = balance(result); return result; }
void insert (Item **base, char *name, char *desc, int price, char *shelf, int amount) { //Perform insert if ((*base) == NULL) { *base = createItem(name, desc, price, shelf, amount); } else if (strcmp(name, (*base)->name) < 0) { insert (&(*base)->left, name, desc, price, shelf, amount); } else if (strcmp(name, (*base)->name) > 0) { insert (&(*base)->right, name, desc, price, shelf, amount); } else if (strcmp(name, (*base)->name) == 0) { addToShelves((*base)->shelves, shelf, amount); } //Update height, this will be done for each ancestor item when traversing back up the recursion path. (*base)->height = max(getHeight((*base)->left), getHeight((*base)->right)) +1; //Get the balance factor to check if this item has an unbalanced subtree int balanceFactor = getBalance(*base); if (balanceFactor < -1 || balanceFactor > 1) { balance(base, name, balanceFactor); } }
void AvlTree::remove(AvlNode * & v, int x) { if (v == NULL) return; if (x < v->key) remove(v->left, x); else if (x > v->key) remove(v->right, x); else//x == v->key { // if at least one child is NULL if (v->left == NULL || v->right == NULL) { AvlNode * garbageNode = v; if (v->right == NULL) v = v->left; else v = v->right; } else // v has two children { AvlNode * u = v->right; //find the smallest key on the right subtree of v while(u->left != NULL) u = u->left; //assign the key value of u to v v->key = u->key; //remove the node u from the right subtree of v remove(v->right,u->key); } } balance(v); }
void setq(Char *name, Char **vec, struct varent *p) { struct varent *c; int f; f = 0; /* tree hangs off the header's left link */ while ((c = p->v_link[f]) != NULL) { if ((f = *name - *c->v_name) == 0 && (f = Strcmp(name, c->v_name)) == 0) { blkfree(c->vec); goto found; } p = c; f = f > 0; } p->v_link[f] = c = (struct varent *) xmalloc((size_t) sizeof(struct varent)); c->v_name = Strsave(name); c->v_bal = 0; c->v_left = c->v_right = 0; c->v_parent = p; balance(p, f, 0); found: trim(c->vec = vec); }
void Character::SaveCharacter() { _log( ITEM__TRACE, "Saving character %u.", itemID() ); sLog.Debug( "Character::SaveCharacter()", "Saving all character info and skill attribute info to DB for character %s...", itemName().c_str() ); // character data m_factory.db().SaveCharacter( itemID(), CharacterData( accountID(), title().c_str(), description().c_str(), gender(), bounty(), balance(), securityRating(), logonMinutes(), corporationID(), allianceID(), warFactionID(), stationID(), solarSystemID(), constellationID(), regionID(), ancestryID(), careerID(), schoolID(), careerSpecialityID(), startDateTime(), createDateTime(), corporationDateTime() ) ); // corporation data m_factory.db().SaveCorpMemberInfo( itemID(), CorpMemberInfo( corporationHQ(), corpRole(), rolesAtAll(), rolesAtBase(), rolesAtHQ(), rolesAtOther() ) ); // Save this character's own attributes: SaveAttributes(); // Loop through all skills and invoke mAttributeMap.SaveAttributes() for each std::vector<InventoryItemRef> skills; GetSkillsList( skills ); std::vector<InventoryItemRef>::iterator cur, end; cur = skills.begin(); end = skills.end(); for(; cur != end; cur++) cur->get()->SaveAttributes(); //cur->get()->mAttributeMap.Save(); }
void insert (int key, struct node** tree) { if (*tree == 0) { printf("i inserting... %d\n", key); *tree = (struct node*)malloc(sizeof(struct node)); (*tree)->key = key; (*tree)->lower = 0; (*tree)->higher = 0; } else if (key < (*tree)->key) { printf("i lower...\n"); insert(key, &(*tree)->lower); } else if (key > (*tree)->key) { printf("i higher...\n"); insert(key, &(*tree)->higher); } *tree = balance(*tree); }
int main(int argc, char** argv) { auto lib = Omega_h::Library(&argc, &argv); auto world = lib.world(); if (argc != 4) { if (!world->rank()) { std::cout << "usage: " << argv[0] << " in.osh <nparts> out.osh\n"; } return -1; } auto nparts_total = world->size(); auto path_in = argv[1]; auto nparts_out = atoi(argv[2]); auto path_out = argv[3]; auto t0 = Omega_h::now(); if (nparts_out < 1) { if (!world->rank()) { std::cout << "error: invalid output part count " << nparts_out << '\n'; } return -1; } if (nparts_out > nparts_total) { if (!world->rank()) { std::cout << "error: output part count " << nparts_out << " greater than MPI job size " << nparts_total << '\n'; } return -1; } auto nparts_in = Omega_h::binary::read_nparts(path_in); if (nparts_in > nparts_total) { if (!world->rank()) { std::cout << "error: input part count " << nparts_in << " greater than MPI job size " << nparts_total << '\n'; } return -1; } auto is_in = (world->rank() < nparts_in); auto comm_in = world->split(int(is_in), 0); auto is_out = (world->rank() < nparts_out); auto comm_out = world->split(int(is_out), 0); auto mesh = Omega_h::Mesh(&lib); if (is_in) { Omega_h::binary::read_in_comm(path_in, comm_in, &mesh); if (nparts_out < nparts_in) { Omega_h_fail( "partitioning to a smaller part count not yet implemented\n"); } } if (is_in || is_out) mesh.set_comm(comm_out); if (is_out) { if (nparts_out != nparts_in) mesh.balance(); Omega_h::binary::write(path_out, &mesh); } world->barrier(); auto t1 = Omega_h::now(); auto imb = mesh.imbalance(); if (!world->rank()) { std::cout << "repartitioning took " << (t1 - t0) << " seconds\n"; std::cout << "imbalance is " << imb << "\n"; } }