Ejemplo n.º 1
0
void dijkstra (graph_t *g, int a, int b) {
    int i, j;
    a = a - 'a';
    b = b - 'a';
    for (i = 0; i < g->vertices_len; i++) {
        vertex_t *v = g->vertices[i];
        v->dist = INT_MAX;
        v->prev = 0;
        v->visited = 0;
    }
    vertex_t *v = g->vertices[a];
    v->dist = 0;
    heap_t *h = create_heap(g->vertices_len);
    push_heap(h, a, v->dist);
    while (h->len) {
        i = pop_heap(h);
        if (i == b)
            break;
        v = g->vertices[i];
        v->visited = 1;
        for (j = 0; j < v->edges_len; j++) {
            edge_t *e = v->edges[j];
            vertex_t *u = g->vertices[e->vertex];
            if (!u->visited && v->dist + e->weight <= u->dist) {
                u->prev = i;
                u->dist = v->dist + e->weight;
                push_heap(h, e->vertex, u->dist);
            }
        }
    }
}
int solve(const IntVec& A, const IntVec& B, int k)
{
    IntVec q(k);
    int n = 0;
    int NA = A.size() >= k ? k : A.size();
    int NB = B.size() >= k ? k : B.size();

    for (int i = 0; i < NA; ++i) {
        for (int j = 0; j < NB; ++j) {
            int s = A[i] + B[i];
            if (n == k) {
                if (s < q[0]) {
                    pop_heap(q.begin(), q.end());
                    q[n - 1] = A[i] + B[j];
                    push_heap(q.begin(), q.begin() + n);
                }
            } else {
                q[n++] = A[i] + B[j];
                push_heap(q.begin(), q.begin() + n);
            }
            //			cout << n << "," << q << endl;
        }
    }
    //	cout << q << endl;
    return q[0];
}
 ListNode* mergeKLists(vector<ListNode*>& lists) {        
     vector<ListNode *> minHeap;
     for (auto list: lists) {
         if (list != nullptr) {
             minHeap.push_back(list);
         }
     }
     make_heap(minHeap.begin(), minHeap.end(), compare);
     
     ListNode *res = new ListNode(-1);
     ListNode *cur = res;
     
     while (!minHeap.empty()) {
         pop_heap(minHeap.begin(), minHeap.end(), compare);
         ListNode *node = minHeap.back();
         minHeap.pop_back();
         
         cur->next = node;
         cur = cur->next;
         
         
         if (node->next) {
             minHeap.push_back(node->next);
             push_heap(minHeap.begin(), minHeap.end(), compare);
         }
     }
     
     return res->next;
 }
Ejemplo n.º 4
0
  /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item
   * in the news feed must be posted by users who the user followed or by the
   * user herself. Tweets must be ordered from most recent to least recent. */
  vector<int> getNewsFeed(int userId) {
    vector<pair<Tweet *, Tweet *>> h;
    for (const int &u : following[userId]) {
      vector<Tweet> &t = tweets[u];
      if (t.size() > 0) {
        h.emplace_back(t.data(), t.data() + t.size() - 1);
      }
    }

    auto &t = tweets[userId];
    if (t.size() > 0) {
      h.emplace_back(t.data(), t.data() + t.size() - 1);
    }
    auto f = [](const pair<Tweet *, Tweet *> &x,
                const pair<Tweet *, Tweet *> &y) {
      return x.second->time > y.second->time;
    };
    make_heap(h.begin(), h.end(), f);
    const int nums = 10;
    vector<int> result;
    result.reserve(nums);
    for (int i = 0; i < nums && !h.empty(); ++i) {
      pop_heap(h.begin(), h.end(), f);
      pair<Tweet *, Tweet *> &next = h.back();
      result.push_back(next.second->id);
      if (next.first == next.second--)
        h.pop_back();
      else
        push_heap(h.begin(), h.end(), f);
    }
    return result;
  }
Ejemplo n.º 5
0
void TimerBase::heapDecreaseKey()
{
    ASSERT(m_nextFireTime != 0);
    checkHeapIndex();
    push_heap(TimerHeapIterator(0), TimerHeapIterator(m_heapIndex + 1));
    checkHeapIndex();
}
bool Graph::pfs()
{
    int v, j, ww, x;
    bool caled[MaxVertex];
    int wt[MaxVertex];
    vector<Node> myheap;
    memset(father, 0xff, sizeof(int)*V);
    memset(caled, 0, sizeof(bool)*V);
    memset(wt, 0xff, sizeof(int)*V);
    myheap.clear();
    father[s] = s;
    myheap.push_back(Node(s, INT_MAX));
    // assert(s != t);
    while(!myheap.empty())
    {
        v = myheap[0].v;
        ww = myheap[0].wt;
        pop_heap(myheap.begin(), myheap.end(), cmp);
        myheap.pop_back();
        if(caled[v]) continue;
        caled[v] = 1;
        for(j = 0; j < V; ++j)
            if(cap[v][j]>0 && !caled[j])
            {
                x = ww<cap[v][j] ? ww : cap[v][j];
                if(x <= wt[j]) continue;
                father[j] = v;
                if(j == t) return 1;
                wt[j] = x;
                myheap.push_back(Node(j, x));
                push_heap(myheap.begin(), myheap.end(), cmp);
            }
    }
    return 0;
}
Ejemplo n.º 7
0
 ListNode *mergeKLists(vector<ListNode *> &lists) {
     if(lists.size() == 0) {
         return NULL;
     }
     vector<ListNode *> nodeHeap;
     for(int i = 0; i < lists.size(); i++) {
         // only push non-NULL node into vector
         if(lists[i] != NULL) {
             nodeHeap.push_back(lists[i]);
         }
     }
     make_heap(nodeHeap.begin(), nodeHeap.end(), cmpNode);
     ListNode *fakeHead = new ListNode(INT_MIN), *curr = fakeHead;
     while(!nodeHeap.empty()) {
         ListNode *tmp = nodeHeap.front();
         curr->next = tmp;
         pop_heap(nodeHeap.begin(), nodeHeap.end(), cmpNode);
         // for the vector, also need to pop back
         // the poped elememt will move to the end of the vector
         nodeHeap.pop_back();
         curr = curr->next;
         // only push non-NULL node into heap
         if(tmp->next != NULL) {
             nodeHeap.push_back(tmp->next);
             push_heap(nodeHeap.begin(), nodeHeap.end(), cmpNode);
         }
     }
     return fakeHead->next;
 }
Ejemplo n.º 8
0
void pop_heap(void *base, size_t n, size_t size,
               int (*cmp)(const void *, const void *)) {
  size_t hole = 1;
  if (n == 0)
    return;

  memswap(base, (char *)base + (n-1) * size, size);

  while (1) {
    size_t child1 = hole * 2;
    size_t child2 = hole * 2 + 1;

    if (child1 >= n)
      break;
    else if (child2 < n)
      if ((*cmp)((const char *)base + (child1-1) * size,
		 (const char *)base + (child2-1) * size) < 0)
	child1 = child2;
    memswap((char *)base + (hole-1) * size,
	    (char *)base + (child1-1) * size, size);
    hole = child1;
  }

  push_heap(base, hole, size, cmp);
}
Ejemplo n.º 9
0
int main () {
  unsigned int n, i;
  unsigned int x;
  double med;

  int v[250000/2+3];

  i = 0;

  cin >> n;
   for(; i < n/2+1; ++i) cin >> v[i];
   make_heap(v,v+n/2+1);
   for(; i < n; ++i){
     cin >> v[n/2+1];
     push_heap(v,v+n/2+2);
     pop_heap(v,v+n/2+2);
   }
    

  if (n % 2 != 0)
    med = v.back();
  else {
    x = v.back();
    v.pop_back();
    med = (v.back()*0.5 + x*0.5);
  }
  cout << setiosflags (ios::fixed) << setprecision(1) << med << endl;   

  return 0;
}
Ejemplo n.º 10
0
	ListNode *mergeKLists(vector<ListNode *> &lists) {
		// wyuan; 10/11/2014; Maitain a min heap. Use make_heap in <algorithm> 
		if(lists.empty())
		    return NULL;
		int size = lists.size();
		// vector<node> heap(size);  Which one is better?
		vector<node> heap;
		heap.reserve(size);
		for(int i = 0; i < size; i++)
			heap.push_back(node(lists[i]));
		make_heap(heap.begin(), heap.end(), greater<node>());
		ListNode *head = new ListNode(0); // Init!!!!!!
		ListNode *pre = head;

		pop_heap(heap.begin(), heap.end(), greater<node>());
		node minNode = heap.back();
		heap.pop_back();

		while(minNode.val != INT_MAX)
		{
			pre->next = minNode.from;
			pre = pre->next;
			ListNode *next = minNode.from->next;
			heap.push_back(node(next));
			push_heap(heap.begin(), heap.end(), greater<node>());			
			pop_heap(heap.begin(), heap.end(), greater<node>());
			minNode = heap.back();
			heap.pop_back();
		}


		ListNode *ret = head->next;
		delete head;
		return ret;
	}
Ejemplo n.º 11
0
Archivo: sort.c Proyecto: errord/sirius
void pop_heap(int a[], int e)
{
  int p;
  int end;
  int h = 1;

  // 最大元素放入顺序位置
  end = a[h-1];
  
  // 回溯到叶子节点
  while ((p = h * 2) < e)
    {
      if (p+1 > e)
        {
          a[h-1] = a[p-1];
          break;
        }
      if (a[p-1] > a[p])
        {
          a[h-1] = a[p-1];
          h = p;
        }
      else
        {
          a[h-1] = a[p];
          h = p+1;
        }
    }
  // 填充空位
  a[h-1] = a[e-1];
  //上溯
  push_heap(a, p/2);
  a[e-1] = end;
}
Ejemplo n.º 12
0
void GridWorld::updateVertex(GridWorld::Tile*& tile){
	bool isIncosistent = tile->rhs != tile->g; //potential problem with floating point comparison?

	if (isIncosistent && tile->isOpen){
		//tile->h = calculateH(tile);
		tile->key = calculateKey(tile);
		make_heap(open.begin(), open.end(), GridWorld::compareTiles);

	}
	else if (isIncosistent && !tile->isOpen){
		//tile->h = calculateH(tile);
		tile->key = calculateKey(tile);
		tile->isOpen = true;

		open.push_back(tile);
		push_heap(open.begin(), open.end(), GridWorld::compareTiles);

	}
	else if (!isIncosistent && tile->isOpen){
		open.erase(std::find(open.begin(), open.end(), tile));
		make_heap(open.begin(), open.end(), GridWorld::compareTiles);
		tile->isOpen = false;
	}

}
Ejemplo n.º 13
0
Archivo: walker.c Proyecto: hvds/seq
whp new_walker(pp_pp* pp, mpz_t limit, int invsum) {
	whp wh;
	walker* w;
	walk_result* wr;
	int numsize = pp->valnumsize;

	wh = arena_size;
	w = WP(wh);
	arena_size += walker_charsize(numsize);
	grow_arena(w, arena_size);
	w->heap = mbh_new(I2P(wh), &mbh_compare_wr);
	w->pp = pp;
	w->numsize = numsize;
	w->adder = pp->adder;
	w->cmper = pp->cmper;
	w->invsum = invsum;
	w->vecsize = (pp->valsize + 31) >> 5;
	w->arenanext = (wrhp)0;
	w->have_previous = 0;
	mpx_set_z(w_limit(w), numsize, limit);

	w_pick_arena(w, wr);
	wr->invsum = 0;
	wr->nextbit = pp->valsize;
	mpx_set_ui(wr_next_discard(w, wr), numsize, 0);
	mpx_set_ui(wr_discard_direct(w, wr), numsize, 0);
	memset(wr_vec_direct(w, wr), 0, w->vecsize * sizeof(int));
	push_heap(w, wr);

	return wh;
}
Ejemplo n.º 14
0
Matrix *merge( Entry* buf, int *counts, int *offsets, int P, std::function<bool(const pair<int,Entry>, const pair<int,Entry>)> reverseSort ) {
  vector<pair<int,Entry> > next;
  int is[P];
  for( int i = 0; i < P; i++ )
    is[i] = 0;
  // initial population of the heap
  for( int i = 0; i < P; i++ )
    if( counts[i] > is[i] ) {
      next.push_back( make_pair( i,buf[offsets[i]+is[i]] ) );
      is[i]++;
    }
  make_heap(next.begin(), next.end(), reverseSort );

  Matrix* ret = new Matrix;
  // put the first entry in the matrix
  if( !next.empty() ) {
    pop_heap(next.begin(), next.end(), reverseSort );
    ret->push_back( next.back().second );
    int i = next.back().first;
    if( counts[i] > is[i] ) {
      next.back().second = buf[offsets[i]+is[i]];
      push_heap(next.begin(), next.end(), reverseSort );
      is[i]++;
    } else {
      next.pop_back();
    }
  }
    
  while( !next.empty() ) {
    pop_heap(next.begin(), next.end(), reverseSort );
    if( ret->back().first.first == next.back().second.first.first &&
	ret->back().first.second == next.back().second.first.second ) {
      ret->back().second += next.back().second.second;
    } else {
      ret->push_back( next.back().second );
    }
    int i = next.back().first;
    if( counts[i] > is[i] ) {
      next.back().second = buf[offsets[i]+is[i]];
      push_heap(next.begin(), next.end(), reverseSort );
      is[i]++;
    } else {
      next.pop_back();
    }
  }
  return ret;
}
Ejemplo n.º 15
0
void landmarked_neighbors<Tdata,Tint>::advance_heap()
{
  int thisGroup,pointIndex,thisPointIndex;
  const Tdata *thisPoint;
  Tdata tmpR2;

  if (!use_landmarks) {
    return;
  }

  // Add points to heap (if necessary).  Here's the scheme &
  // considerations:
  // (1) add all groups that have a lower-bound distance
  //     within the currentR2
  // (2) if the closest point yet has a square distance larger than
  //     currentR2, it might not be the closest point: there might be
  //     another landmark group containing a closer point.  So we increase
  //     currentR2 and add all the groups up to that distance.
  //
  // This leads to a double-while construction.  We could do it with a
  // single-while, but it could result in unnecessary points being
  // added to the heap, if a later group already scheduled for
  // addition has the closest point.
  //mexPrintf("1: currentR2 %g, lmIterator->R2 %g\n",currentR2,lmIterator->R2);
  while (lmIterator < landmarks_sdi.end() && lmIterator->R2 <= currentR2) {
    //mexPrintf("2: currentR2 %g, lmIterator->R2 %g\n",currentR2,lmIterator->R2);
    while (lmIterator < landmarks_sdi.end() && lmIterator->R2 <= currentR2) {
      // Add all the points in the current group
      thisGroup = lmIterator->index;
      //mexPrintf("Adding group %d\n",thisGroup);
      for (pointIndex = 0; pointIndex < lminfo.n_landmarkList[thisGroup]; pointIndex++) {
	thisPointIndex = (int) lminfo.landmarkList[thisGroup][pointIndex] - lminfo.index_offset;
	thisPoint = x + lminfo.d*thisPointIndex;
	tmpR2 = sqrdist(&(*y.begin()),&(*y.end()),thisPoint);
	*point_heap_end = SqrdistIndex<Tdata>(tmpR2,thisPointIndex);
	// make it so the top of the heap is the closest point
	push_heap(point_heap.begin(),++point_heap_end,is_farther<Tdata>());
      }
      //mexPrintf("Heap status:\n");
      //typename vector< SqrdistIndex<Tdata> >::iterator phI;
      //for (phI = point_heap.begin(); phI < point_heap_end; phI++)
      //  mexPrintf("x%d (%g) ",phI->index,phI->R2);
      //mexPrintf("\n");
      lmIterator++;
    } // end of inside while loop
    // We want to make sure we keep including groups until we get some
    // points on the heap that are closer than any points not on the
    // heap.  The way to do that is to adjust currentR2 to reflect the
    // distance to the closest point.
    if (!is_empty())
      currentR2 = point_heap.begin()->R2;
    else if (lmIterator < landmarks_sdi.end()) {
      // If the heap is still empty, but we haven't exhausted all
      // landmarks, then we must have had only empty landmark
      // groups. In that case, increment to the next landmarkR2.
      currentR2 = lmIterator->R2;
    }
  }
}
Ejemplo n.º 16
0
void TimerBase::heapDecreaseKey()
{
    ASSERT(m_nextFireTime != 0);
    checkHeapIndex();
    TimerBase** heapData = timerHeap().data();
    push_heap(TimerHeapIterator(heapData), TimerHeapIterator(heapData + m_heapIndex + 1), TimerHeapLessThanFunction());
    checkHeapIndex();
}
Ejemplo n.º 17
0
void Timer :: AddTimerWithType(const uint64_t llAbsTime, const int iType, uint32_t & iTimerID)
{
    iTimerID = m_iNowTimerID++;

    TimerObj tObj(iTimerID, llAbsTime, iType);
    m_vecTimerHeap.push_back(tObj);
    push_heap(begin(m_vecTimerHeap), end(m_vecTimerHeap));
}
 int add(int val) {
     std::vector<int>& minHeap = *ptMinHeap;
     if (minHeap.size() < _k) {
         minHeap.push_back(val);
         push_heap(minHeap.begin(), minHeap.end(), std::greater<int>());
     } else if (val > minHeap[0]) {
         minHeap[0] = val;
         std::make_heap(minHeap.begin(), minHeap.end(), std::greater<int>());
     }
     return minHeap[0];
 }
Ejemplo n.º 19
0
Archivo: sort.c Proyecto: errord/sirius
void max_heap_sort(int a[], int l)
{
  int i;

  // 构造heap
  for (i = 1; i <= l; i++)
    push_heap(a, i);
  // 序列化
  for (i = l; i > 0; i--)
    pop_heap(a, i);
}
Ejemplo n.º 20
0
void ParticleStorage::deleteParticle(Particle *p)
{
    assert(particles != NULL && p != NULL && available < capacity);
    Particle *q = freeAndAllocatedParticles[available];
    int index = *((int*) (((unsigned char*) p) + particleSize - sizeof(int)));
    *((int*) (((unsigned char*) q) + particleSize - sizeof(int))) = index;
    freeAndAllocatedParticles[index] = q;
    freeAndAllocatedParticles[available++] = p;
    if (pack) {
        push_heap(freeAndAllocatedParticles.begin(), freeAndAllocatedParticles.begin() + available, greater<Particle*>());
    }
}
Ejemplo n.º 21
0
void TestHeapOperations (void)
{
    static const int c_Values [31] = {	// 31 values make a full 4-layer tree
	93, 92, 90, 86, 83, 86, 77, 40, 72, 36, 68, 82, 62, 67, 63, 15,
	26, 26, 49, 21, 11, 62, 67, 27, 29, 30, 35, 23, 59, 35, 29
    };
    vector<int> v;
    v.reserve (VectorSize(c_Values));
    for (uoff_t i = 0; i < VectorSize(c_Values); ++ i) {
	v.push_back (c_Values[i]);
	push_heap (v.begin(), v.end());
	cout << "------------------------------------------------\n";
	if (!is_heap (v.begin(), v.end()))
	    cout << "Is NOT a heap\n";
	PrintHeap (v);
    }
    cout << "------------------------------------------------\n";
    cout << "make_heap on the full range:\n";
    v.resize (VectorSize (c_Values));
    copy (VectorRange(c_Values), v.begin());
    make_heap (v.begin(), v.end());
    PrintHeap (v);
    if (!is_heap (v.begin(), v.end()))
	cout << "Is NOT a heap\n";
    cout << "------------------------------------------------\n";
    cout << "pop_heap:\n";
    pop_heap (v.begin(), v.end());
    v.pop_back();
    PrintHeap (v);
    if (!is_heap (v.begin(), v.end()))
	cout << "Is NOT a heap\n";

    cout << "------------------------------------------------\n";
    cout << "sort_heap:\n";
    v.resize (VectorSize (c_Values));
    copy (VectorRange(c_Values), v.begin());
    make_heap (v.begin(), v.end());
    sort_heap (v.begin(), v.end());
    foreach (vector<int>::const_iterator, i, v)
	cout << *i;
    cout << endl;

    cout << "------------------------------------------------\n";
    cout << "priority_queue push and pop:\n";
    priority_queue<int> q;
    for (uoff_t i = 0; i < VectorSize(c_Values); ++ i)
	q.push (c_Values[i]);
    while (!q.empty()) {
	cout << q.top();
	q.pop();
    }
    cout << endl;
}
Ejemplo n.º 22
0
float KDTreeResultVector::replace_maxpri_elt_return_new_maxpri(KDTreeResult& e) {
    // remove the maximum priority element on the queue and replace it
    // with 'e', and return its priority.
    //
    // here, it means replacing the first element [0] with e, and re heapifying.

    pop_heap( begin(), end() );
    pop_back();
    push_back(e); // insert new
    push_heap(begin(), end() );  // and heapify.
    return( (*this)[0].dis );
}
 void addNum(int num) {
     if (upper.size() == 0) {
         upper.push_back(num);
     } else if (upper.size() == lower.size()) {
         if (num > lower[0]) {
             upper.push_back(num);
             push_heap(upper.begin(), upper.end(), greater<int>());
         } else {
             lower.push_back(num);
             push_heap(lower.begin(), lower.end());
             int val = lower[0];
             pop_heap(lower.begin(), lower.end());
             lower.pop_back();
             upper.push_back(val);
             push_heap(upper.begin(), upper.end(), greater<int>());
         }
     } else {
         if (num > upper[0]) {
             upper.push_back(num);
             push_heap(upper.begin(), upper.end(), greater<int>());
             int val = upper[0];
             pop_heap(upper.begin(), upper.end(), greater<int>());
             upper.pop_back();
             lower.push_back(val);
             push_heap(lower.begin(), lower.end());
         } else {
             lower.push_back(num);
             push_heap(lower.begin(), lower.end());
         }
     }
 }
Ejemplo n.º 24
0
	void add_path(const SeqPath& path)
	{
		if (path.path_score<=score_pairs[0].score)
			return;
		
		const int pos = score_pairs[0].pos;
		paths[pos]=path;

		pop_heap(score_pairs.begin(),score_pairs.end());
		score_pairs[heap_size-1].pos = pos;
		score_pairs[heap_size-1].score = path.path_score;
		push_heap(score_pairs.begin(),score_pairs.end());
	}
Ejemplo n.º 25
0
//扩展节点
void CAstar::ExtendNode(CAstarNode* s)
{
	vector<Point> neighbor = GetNeighbor(s->m_hgevCoordinate);

	for(vector<Point>::iterator iter1 = neighbor.begin(); iter1 != neighbor.end(); iter1++)
	{
		bool exist = false;
		vector<CAstarNode>::iterator iter2 = m_vClosedList.begin();
		for(; iter2 != m_vClosedList.end(); iter2++)
		{
			if((*iter1) == (*iter2).m_hgevCoordinate)
			{
				exist = true;
				break;
			}
		}
		//节点在close表中,跳过该节点
		if(exist)
			continue;

		//计算该节点的确定耗费
		int tentative_g = s->m_nG;

		if((abs((*iter1).x-s->m_hgevCoordinate.x) + abs((*iter1).y-s->m_hgevCoordinate.y)) == 1)
			tentative_g += DEMO::MOVE_MIN_STEP;
		else
			tentative_g += DEMO::MOVE_MAX_STEP;

		iter2 = m_vOpenList.begin();
		for(; iter2 != m_vOpenList.end(); iter2++)
		{
			if((*iter1) == (*iter2).m_hgevCoordinate)
			{
				exist = true;
				break;
			}
		}
		//节点不在open表中,则添加到open表中
		if(!exist)
		{
			CAstarNode temp(*iter1,tentative_g,CalculateH(*iter1),s);
			m_vOpenList.push_back(temp);
			push_heap(m_vOpenList.begin(),m_vOpenList.end(),cmpAstarNode);
		}
		//否则若g小于open表中该节点的g值,则更新表中的g
		else if((*iter2).m_nG > tentative_g)
		{
			(*iter2).m_nG = tentative_g;	
		}
	}
}
Ejemplo n.º 26
0
void heap_algo(){
    cout<<endl<<"set_algo :"<<endl;
    int ia1[9] = {0, 1, 2, 3, 4, 8, 9 , 3 , 5 };
    vector<int> ivec(ia1,ia1+9);
    make_heap(ivec.begin(),ivec.end(),greater<int>());		//默认最大堆,这样就是最小堆
    cout<<ivec<<endl;
    ivec.push_back(7);
    push_heap(ivec.begin(),ivec.end(),greater<int>());		//对新加入的元素调整位置
    cout<<ivec<<endl;
    pop_heap(ivec.begin(),ivec.end(),greater<int>());			//堆首删除放到容器尾
    ivec.pop_back();
    cout<<ivec<<endl;
    sort_heap(ivec.begin(),ivec.end(),greater<int>());			//堆排序
    cout<<ivec<<endl;
}
Ejemplo n.º 27
0
void Word2Vec::create_huffman_tree()
{
	size_t vocab_size = vocab.size();

	vector<Word *> heap = vocab;
	make_heap(heap.begin(), heap.end(), comp);

	for(size_t i = 0; i < vocab_size - 1; ++i)
	{
		pop_heap(heap.begin(), heap.end(), comp);
		Word *min_left = heap.back(); heap.pop_back();
		pop_heap(heap.begin(), heap.end(), comp);
		Word *min_right = heap.back(); heap.pop_back();

		Word *w = new Word(i + vocab_size, min_left->count + min_right->count, "", min_left, min_right);
		heap.push_back(w);
		push_heap(heap.begin(), heap.end(), comp);
	}

	//traverse huffman tree,get code
	list<tuple<Word *, vector<size_t>, vector<size_t>>> stack;
	stack.push_back(make_tuple(heap[0],  vector<size_t>(), vector<size_t>()));
	while(!stack.empty())
	{
		auto n = stack.back();
		stack.pop_back();

		Word *n_w = get<0>(n);
		if(n_w->index < vocab_size)
		{
			n_w->codes = get<1>(n);
			n_w->points = get<2>(n);
		}
		else
		{
			auto codes_left = get<1>(n);
			auto codes_right = codes_left;
			codes_left.push_back(0); 
			codes_right.push_back(1);

			auto points = get<2>(n);
			points.emplace_back(n_w->index - vocab_size);

			stack.emplace_back(make_tuple(n_w->left, codes_left, points));
			stack.emplace_back(make_tuple(n_w->right, codes_right, points));
		}
	}
}
Ejemplo n.º 28
0
/* store the alpha values and build a beta_tree for the generator */
void gen_dirch_initialize(gen_dirch_param *gen, int numd, const double *alp)
{
    int *heap;	int heap_size;
    int leaf, internal;	/* indexes of nodes in tree */
    double *alpha;	/* shorthand pointer for gen->alpha */
    
    gen->num_dim = numd;
    
    /* allocate space for the alphas---both for the leaves and the
     * internal nodes
     */
    gen->alpha = alpha = (double*)calloc(2*numd-1, sizeof(double));
    assert(gen->alpha);
    
    /* allocate space for the internal nodes */
    gen->betas = (gen_beta_param*) calloc(numd-1, sizeof(gen_beta_param));
    assert(gen->betas);
    gen->left = (int*) calloc(numd-1, sizeof(int));
    assert(gen->left);
    gen->right = (int*) calloc(numd-1, sizeof(int));
    assert(gen->right);
    
    /* Build a "Huffman encoding" tree using a heap.
     * First, fill the heap array with the indexes of the leaves
     */
    heap = (int*)calloc(numd, sizeof(int));
    for (leaf=numd-1; leaf>=0; leaf--)
    {  alpha[leaf] = alp[leaf];
        heap[leaf] = leaf;
    }
    heapify(heap, alpha, numd);
    
    heap_size=numd;
    internal = 0;	/* number of internal nodes created so far */
    while(heap_size>=2)
    {   gen->left[internal] = pop_heap(heap, alpha, &heap_size);
    	gen->right[internal] = pop_heap(heap, alpha, &heap_size);
        gen_beta_initialize(&(gen->betas[internal]), 
                            alpha[gen->left[internal]], alpha[gen->right[internal]]);
        alpha[internal+numd] =	alpha[gen->left[internal]] 
        + alpha[gen->right[internal]];
        push_heap(heap, alpha, &heap_size, internal+numd);
        internal++;
    }
    gen->root_index = internal+numd-1;
    assert(gen->root_index == 2*numd-2);
    free(heap);
}
Ejemplo n.º 29
0
PWDB* pw_aln_contigs(CtgDB *db) {
	uint32_t i, j, n;
	int k, mn, mm, off0, off1, aln_len;
	PWDB *pwdb;
	Ctg *c0, *c1;
	pwdb = (PWDB*)malloc(sizeof(PWDB));

	pwdb->pwctgs = init_pwctglist(6);
	pwdb->hp = init_heap(aln_cmp, pwdb);
	pwdb->ctgv = db->ctgs;
	AlnParam ap = {10, 2, 2, aln_sm_nt, 16, 75};

	n = db->ctgnum;
	
	for (i = 0; i < n-1; i++) {
		c0 = ref_ctglist(db->ctgs, i);
		for (j = i+1; j < n; j++) {
			c1 = ref_ctglist(db->ctgs, j);
			AlnAln *aa;
			mn = mm = 0;
			off0 = off1 = -1;
			aa = aln_stdaln(c0->seq, c1->seq, &ap, 0, 1);
			aln_len = strlen(aa->out1);
			for (k = 0; k < aln_len; k++) {
				if (aa->out1[k] == '-' || aa->out2[k] == '-') continue;
				if (aa->out1[k] != aa->out2[k]) mm++;
				mn++;
			}
			PWcontig *pwc = (PWcontig*)malloc(sizeof(PWcontig));
			pwc->id0 = c0->cls_id;
			pwc->id1 = c1->cls_id;
			pwc->overlap = mn;
			pwc->score = aa->score;
			pwc->het = (float)mm/mn; 
			push_heap(pwdb->hp, pwc);
			push_pwctglist(pwdb->pwctgs, pwc);
			//fprintf(stdout, "%d\t%d\t%d\t%d\t%d\t%d\t%.3f\n", c0->cls_id, c1->cls_id, pwc->id0, pwc->id1, mn, mm, pwc->het);
			//fprintf(stdout, "%s\n%s\n", c0->seq, c1->seq);
			//fprintf(stdout, "%d\t%d\t%d\t%d\t%d\t%d\n%s\n%s\n%s\n\n", aa->start1, aa->end1,aa->start2, aa->end2, pwc->score, pwc->overlap, aa->out1, aa->outm, aa->out2);

			//fprintf(stdout, "%s\n%s\n%s\n\n", aa->out1, aa->outm, aa->out2);
			fflush(stdout);
			aln_free_AlnAln(aa);
		}
	}

	return pwdb;
}
Ejemplo n.º 30
0
// Add a node to the heap
void
CbcTree::push(CbcNode * x)
{
    x->setNodeNumber(maximumNodeNumber_);
    maximumNodeNumber_++;
    /*printf("push obj %g, refcount %d, left %d, pointing to %d\n",
       x->objectiveValue(),x->nodeInfo()->decrement(0),
       x->nodeInfo()->numberBranchesLeft(),x->nodeInfo()->numberPointingToThis());*/
    assert(x->objectiveValue() != COIN_DBL_MAX && x->nodeInfo());
#ifdef JJF_ZERO
    nodes_.push_back(x);
    push_heap(nodes_.begin(), nodes_.end(), comparison_);
#else
realpush(x);
#endif
}