VectorXf GeodesicDistance::compute(int nd) const {
	PQ q;
	q.push( Node( nd, 0 ) );
	VectorXf d = 1e10*VectorXf::Ones( N_ );
	updatePQ( d, q );
	return d;
}
Example #2
0
void benchOpsThread(bench_ops_thread_arg_t * arg)
{
    wbmm_thread_init(arg->tid);

    uint32_t seed1 = arg->tid;
    uint32_t seed2 = seed1 + 1;

    uint64_t ops = 0;
    PQ * set = (PQ *)arg->set;

    while (!bench_begin);

    while (!bench_stop) {
        int op  = rand_r_32(&seed1) % 100;
        int key = rand_r_32(&seed2) % KEY_RANGE;
        if (op < 50) {
            set->add(key);
        }
        else {
            key = set->remove();
        }
        for (int i = 0; i < DELAY; i++) spin64();
        ops++;
    }
    arg->ops = ops;
}
Example #3
0
int dijdij(int st,int ed){
    v[0].reset(); v[1].reset();
    for(int i=0;i<111;++i)d[i].clear();
    d[st].pb(0);
    PQ<pii,vector<pii>,greater<pii>> pq; pq.push({0,st});
    while(pq.size()){
        while(pq.size() && v[1][pq.top().Y])pq.pop();
        if(pq.empty())break;
        pii now=pq.top(); pq.pop();
        int stp=v[0][now.Y]?1:0;
        PDE3(now,stp,pq);
        v[stp][now.Y]=1;
        for(pii e:G[now.Y]){
            d[e.X].pb(now.X+e.Y);
            sort(d[e.X].begin(),d[e.X].end());
            d[e.X].resize(unique(d[e.X].begin(),d[e.X].end())-d[e.X].begin());
            if(d[e.X].size()>2u){
                sort(d[e.X].begin(),d[e.X].end());
                d[e.X].pop_back();
            }
            if(now.X+e.Y<=d[e.X].back()){
                pq.push({now.X+e.Y,e.X});
            }
        }
    }
    if(d[ed].size()<2u)return -1;
    else return d[ed][1];
}
GeodesicDistance& GeodesicDistance::update( const VectorXf &new_min ) {
	PQ q;
	for( int i=0; i<N_; i++ )
		if( new_min[i] < d_[i] )
			q.push( Node( i,new_min[i] ) );
	updatePQ( d_, q );
	return *this;
}
Example #5
0
  /*! 
    Transforms the queue into a vector of indeces to points and returns it
    \param pl Vector which will hold the answer after function completes 
  */
  void answer(vector<long unsigned int>& pl)
  {
    pl.resize(K);
    for(int i=pl.size()-1;i >= 0;--i)
      {
	pl[i] = pq.top().second;
	pq.pop();
      }
  };
VectorXf GeodesicDistance::compute(const VectorXf &start) const {
	PQ q;
	for( int i=0; i<N_; i++ )
		if( start[i] < 1e5 )
			q.push( Node( i, start[i] ) );
	VectorXf d = 1e10*VectorXf::Ones( N_ );
	updatePQ( d, q );
	return d;
}
Example #7
0
  /*! 
    Transforms the queue into a vector of indeces to points and a 
    vector of squared distances
    \param pl Vector which holds the point indeces after function completes
    \param pd Vector which holds the squared distances from query point
  */
  void answer(vector<long unsigned int>& pl, vector<double> &pd)
  {
    pl.resize(K);
    pd.resize(K);
    for(int i=pl.size()-1;i >= 0; --i)
      {
	pl[i] = pq.top().second;
	pd[i] = pq.top().first;
	pq.pop();
      }
  }
Example #8
0
void test2() {
  PQ p;
  for (int i = 0;i < 10;i++) {
    p.push(10-i);
  }

  while (p.empty() == false) {
    cout << p.top() << endl;
    p.pop();
  }
}
Example #9
0
static bool sanityCheck()
{
    PQ set;

    uint32_t seed = 0;
    for (uint32_t i = 0; i < INIT_SIZE; i++) {
        int key = rand_r_32(&seed) % KEY_RANGE;
        set.add(key);
    }

    bench_begin = false;
    bench_stop = false;

    thread *              thrs[NUM_THREADS];
    sanity_thread_arg_t   args[NUM_THREADS];

    for (uint32_t j = 0; j < NUM_THREADS; j++) {
        sanity_thread_arg_t & arg = args[j];
        arg.tid = j + 1;
        arg.set = &set;
        arg.ops = 0;
        thrs[j] = new thread(sanityThread<PQ>, &arg);
    }

    // broadcast begin signal
    bench_begin = true;
    sleep(DURATION);
    bench_stop = true;

    for (uint32_t j = 0; j < NUM_THREADS; j++) thrs[j]->join();

    uint32_t old = 0;
    for (uint32_t i = 0; i < INIT_SIZE; i++) {
        uint32_t num = set.remove();
        if (old > num) {
            cout << "error: heap invariant violated: "
                      << "prev = " << old << " "
                      << "curr = " << num << endl;
            return false;
        }
        if (num == PQ_VAL_MAX) {
            cout << "error: missing element(not linearizable)" << endl;
            return false;
        }
        old = num;
    }
    uint32_t num = set.remove();
    if (num != PQ_VAL_MAX) {
        cout << "error: extra element(not linearizable)" << endl;
        return false;
    }
    cout << "Sanity check: okay." << endl;
    return true;
}
Example #10
0
int main(){
    // freopen("in","r",stdin);
    // freopen("out","w",stdout);
    int ks=0,n,m;while(rit(n,m),n){
        while(m--){
            int a,b,l;rit(a,b,l);
            G[a].pb({b,l}); G[b].pb({a,l});
        }
        pq.push({1,0});
        while(pq.size()){
            while(v[pq.top().X])pq.pop();
            v[pq.top().X]=1;
            
        }
    }
}
Example #11
0
void
pq_delete_min(PQ pq, void *retval)
{
    int floater;        /* previous loser floating down */
    int small_child;    /* smaller child of floater */

    assert(!pq_is_empty(pq));

    /* first copy out the winner */
    memcpy(retval, REF(pq, 0), pq->element_length);

    --(pq->n);

    if(pq_is_empty(pq)) {
        /* pq empty, nothing to do */
        return;
    }

    /* else */
    memcpy(REF(pq, 0), REF(pq, pq->n), pq->element_length);

    floater = 0;

    for(;;) {
        /* find smaller child of floater */
        if(Child(floater, 0) >= pq->n) {
            return;     /* no children, bail out */
        } else if(Child(floater, 1) >= pq->n) {
            small_child = Child(floater, 0);
        } else if(pq->compare(REF(pq, Child(floater, 0)), REF(pq, Child(floater, 1))) < 0) {
            small_child = Child(floater, 0);
        } else {
            small_child = Child(floater, 1);
        }

        /* is floater <= small_child? */
        if(pq->compare(REF(pq, floater), REF(pq, small_child)) <= 0) {
            /* yes, we are done */
            return;
        } else {
            /* no, swap and continue floating down */
            pq_swap(pq, floater, small_child);
            floater = small_child;
        }
    }
}
Example #12
0
  /*! 
    Updates the queue with the given distance and point
    \param dist Distance of point to be added
    \param p index of point to be added
    \return True if a point was added to the queue
  */
  bool update(double dist, long int p)
  {
    if(size() < K)
      {
	q_intelement tq(dist, p);
	pq.push(tq);
	return true;
      }
    else if(topdist() > dist)
      {
	pq.pop();
	q_intelement tq(dist, p);
	pq.push(tq);
	return true;
      }
    return false;
  }
Example #13
0
void  testHeap ( int n ) {
   T* A = new T[2*n/3]; //创建容量为2*n/3的数组,并
   for ( int i = 0; i < 2 * n / 3; i++ ) A[i] = dice ( ( T ) 3 * n ); //在其中随机生成2*n/3个词条
   /*DSA*/printf ( "%d random keys created:\n", 2 * n / 3 );
   /*DSA*/for ( int i = 0; i < 2 * n / 3; i++ ) print ( A[i] ); printf ( "\n" );
   PQ heap ( A + n / 6, n / 3 ); //批量建堆(PQ_ComplHeap实现了Robert Floyd算法)
   delete [] A;
   /*DSA*/system("cls"); print ( heap );  Sleep(100);
   while ( heap.size() < n ) { //随机测试
      if ( dice ( 100 ) < 70 ) { //70%概率插入新词条
         T e = dice ( ( T ) 3 * n ); /*DSA*/printf ( "Inserting" ); print ( e ); printf ( " ...\n" );
         heap.insert ( e ); /*DSA*/printf ( "Insertion done\n" );
      } else { //30%概率摘除最大词条
         if ( !heap.empty() ) {
            /*DSA*/printf ( "Deleting max ...\n" );
            T e = heap.delMax();/*DSA*/printf ( "Deletion done with" ); print ( e ); printf ( "\n" );
         }
      }
      /*DSA*/system("cls"); print ( heap ); Sleep(100);
   }
   while ( !heap.empty() ) { //清空
      T e = heap.delMax();/*DSA*/printf ( "Deletion done with" ); print ( e ); printf ( "\n" );
      /*DSA*/system("cls"); print ( heap ); Sleep(100);
   }
}
Example #14
0
static void runBench()
{
    PQ set;

    uint32_t seed = 0;
    for (uint32_t i = 0; i < INIT_SIZE; i++) {
        int key = rand_r_32(&seed) % KEY_RANGE;
        set.add(key);
    }

    bench_begin = false;
    bench_stop = false;

    thread *                 thrs[NUM_THREADS];
    bench_ops_thread_arg_t   args[NUM_THREADS];

    for (uint32_t j = 0; j < NUM_THREADS; j++) {
        bench_ops_thread_arg_t & arg = args[j];
        arg.tid = j + 1;
        arg.set = &set;
        arg.ops = 0;
        thrs[j] = new thread(benchOpsThread<PQ>, &arg);
    }

    // broadcast begin signal
    bench_begin = true;

    sleep(DURATION);

    bench_stop = true;

    for (uint32_t j = 0; j < NUM_THREADS; j++)
        thrs[j]->join();

    uint64_t totalOps = 0;
    for (uint32_t j = 0; j < NUM_THREADS; j++) {
        totalOps += args[j].ops;
    }

    cout << ("Throughput(ops/ms): ")
         << std::setprecision(6)
         << (double)totalOps / DURATION / 1000 << endl;
}
Example #15
0
/**
  *Requires that all Tree Nodes representing Active Characters have been created
  *And Enqueued into the Priorty Queue
  *Generates a huffman tree by combining the nodes in th PQ
  *the root of the tree is at the head of the priorty queue
*/
	void Huffman:: HuffHuff()		//now it creates the huffman tree
	{
   	if(!(q->getSize1())) //single element
         q->enq(mTreeNodes(q->deq(),NULL));
		while(q->getSize1())
		{
			q->enq(mTreeNodes(q->deq(),q->deq()));
		}
		cout<<"\n\n\t\tLegend Tree along with char at end\n"<<endl;
		q->getHead()->displayTree();
		system("pause");
	}
Example #16
0
//Insert limit elements of the file fin into heap.
void insertNext(PQ & pq, ifstream & fin, int limit = 0)
{
	if (limit == 0)
		limit = numeric_limits<int>::max();
	string word;
	int ct;
	while (!fin.eof() && pq.size < limit){
		fin >> word >> ct;
		pq.insert(ItemType(word, ct));
	}
}
Example #17
0
void sanityThread(sanity_thread_arg_t * arg)
{
    wbmm_thread_init(arg->tid);

    uint32_t seed1 = arg->tid;
    uint32_t seed2 = seed1 + 1;

    uint64_t ops = 0;
    PQ * set = (PQ *)arg->set;

    while (!bench_begin);

    while (!bench_stop) {
        int key = rand_r_32(&seed2) % KEY_RANGE;
        set->add(key);
        key = set->remove();
        ops++;
    }
    arg->ops = ops;
}
Example #18
0
int main() {
    int n, m;
    scanf("%d %d", &n, &m);

    vector<vector<pii>> edges(n);
    while(m--) {
        int u, v, w;
        scanf("%d %d %d", &u, &v, &w);
        edges[u].push_back({w, v});
        edges[v].push_back({w, u});
    }

    PQ pq;
    pq.push({0,0});
    while(!pq.empty()) {
        int dist = pq.top().first;
        int curr = pq.top().second;
        pq.pop();

        if (vis[curr] != false) continue;
        vis[curr] = true;

        /*
         * curr visited in "shortest path" order here
         */

        for(pii it : edges[curr]) {
            int ndist = it.first + dist;
            int next = it.second;
            pq.push({ndist, next});
        }
    }

    return 0;
}
Example #19
0
int dijkstra(int start ,int goal ,int maxRank)
	{
	memset(dis , 0x7F ,sizeof(dis));
	memset(apr , 0 	  ,sizeof(apr));
	dis [start] = 0;
	que . size =0;
	que . push(start);
	while(!que . empty())
		{
		PQNode t;
		bool notGet = true;
		while(!que . empty())
			{
			t = que.top();
			que.pop();
			if(!apr[t . no]) 
				{
				notGet = false;
				break;
				}
			}
		if(notGet)break;
		for(Node *p = adj[t . no];p ; p=p->next)
			{
			if( rank [p->y] > maxRank) continue;
			if( rank [p->y] < maxRank - limRank) continue;
			if(dis[p->y] > dis[t .no] + p->w)
				{
				dis[p->y] = dis[t .no] + p->w;
				que .push(p->y);
				}
			}
		apr [t. no] = true;
		}
	if( !apr[goal] ) return -1;
	return dis [goal];
	}
Example #20
0
bool sanityCheckSequential()
{
    const int max = 10000;
    std::priority_queue<int32_t, vector<int32_t>, pqcompare> contrast;
    PQ m;
    uint32_t seed = 0;
    for (int i = 0; i < max; i++) {
        int32_t temp = rand_r_32(&seed) % KEY_RANGE;
        contrast.push(temp);
        m.add(temp);
    }
    for (int i = 0; i < max - 1; i++) {
        uint32_t r1 = m.remove();
        uint32_t r2 = contrast.empty() ? PQ_VAL_MAX : contrast.top();
        if (!contrast.empty()) contrast.pop();
        if (r1 != r2) {
            cout << "different element at index " << i << ":"
                 << r1 << " " << r2 <<  endl;
            return false;
        }
    }
    cout << "Sanity check: okay." << endl;
    return true;
}
Example #21
0
void test1() {
  PQ p;
  p.push(1);
  p.push(2);
  p.push(3);
  p.push(4);
  p.push(5);

  while (p.empty() == false) {
    cout << p.top() << endl;
    p.pop();
  }

}
Example #22
0
void
pq_sanity_check(PQ pq)
{
    int i;
    int j;

    assert(pq->n >= 0);
    assert(pq->n <= pq->size);

    for(i = 0; i < pq->n; i++) {
        for(j = 0; j < NUM_CHILDREN; j++) {
            if(Child(i, j) < pq->n) {
                assert(pq->compare(REF(pq, i), REF(pq, Child(i, j))) <= 0);
            }
        }
    }
}
Example #23
0
// find top-k CC using boost graph representation
PQ find_top_CC(DeterministicGraph& PW, int k) {
	typename graph_traits <DeterministicGraph>::out_edge_iterator out1, out2;

	PQ pq; // priority queue for top-k CC
	int V = num_vertices(PW);
	bool *explored = new bool[V+1];
	for (int i = 0; i < V; ++i)
		explored[i] = false;
	int cc_number = 0;
	int unit_sized = 0;

	for (int i = 0; i < V; ++i) {
		if (!explored[i]) {
			// perform BFS for vertex i
			vector<int> CC;
			CC.push_back(i);
			explored[i] = true;
			vector<int>::size_type ix = 0;
			while (ix < CC.size()) {
				Vertex u = vertex(CC[ix], PW);
				for (tie(out1, out2) = out_edges(u, PW); out1 != out2; ++out1) {
					Vertex v = target(*out1, PW);
					if (!explored[v]) {
						CC.push_back(v);
						explored[v] = true;
					}
				}
				ix++;
			}
//			if (CC.size() > 5)
//				cout << cc_number << ": " << CC.size() << endl;
			if (CC.size() == 1) {
				unit_sized++;
			}
			cc_number++;

			// maintain CC priority queue
			int pq_size = pq.size();
			if (pq_size == k) {
				vector<int> top = pq.top();
				if (top.size() < CC.size()) {
					pq.pop();
					pq.push(CC);
				}
			}
			else
				pq.push(CC);
		}
	}
//	cout << "Total CCs: " << cc_number << endl;
//	cout << "Unit CCs: " << unit_sized << endl;
	return pq;
}
Example #24
0
int main(){
    while(scanf("%d%d",&n,&m)!=EOF,n){
        init();
        for(int i=0,a,b,p,t;i<m;i++){
            a=rit(),b=rit(),p=rit(),t=rit();
            g[a][b]={t,p};
        }
        nb=rit(),ne=rit();
        rT(STst),rT(STed);
        ts=getT(STst);te=getT(STed);

        PQ<_pq,vector<_pq>,greater<_pq>> pq;
        pq.push({nb,ts});
        for(int _i=0;_i<n;++_i){
            while(S(pq)&&v[pq.top().pt]){
                pq.pop();
            }
            if(S(pq)==0)break;
            v[pq.top().pt]=1;
            d[pq.top().pt]=pq.top().tm;
            int np=pq.top().pt,nt=pq.top().tm;
            for(int i=1;i<=n;++i){                          // waiting time
                if(g[np][i].lo!=0 && d[i]>d[np]+g[np][i].lo+(g[np][i].ev-(d[np]%g[np][i].ev)%g[np][i].ev)){
                    d[i]=d[np]+g[np][i].lo+(g[np][i].ev-(d[np]%g[np][i].ev)%g[np][i].ev);
                    pq.push({i,d[np]+g[np][i].lo+(g[np][i].ev-(d[np]%g[np][i].ev)%g[np][i].ev)});
                }
            }
        }
        cout<<ts<<" "<<te<<endl;
        if(d[ne]==0x7f7f7f7f){
            printf("No way\n");
            continue;
        }
        else{
            printf("--%d--\n",d[ne]);
        }
    }
}
int dijkstra() {
  REP(i,n) REP(j,c+1) d[i][j] = INF, visited[i][j] = false;
  
  d[s][0] = 0;

  PQ pq;
  pq.push(State(s, 0, 0));

  while(!pq.empty()) {
    State u = pq.top(); pq.pop();

    if(u.node == e and u.fuel == 0) return u.cost;
    if(visited[u.node][u.fuel]) continue;

    visited[u.node][u.fuel] = true;
    /*
    // Create other states, when I just buy fuel
    int cost = u.cost; // current cost of fuel
    for(int f = u.fuel+1; f <= c; f++) { // try to fill until reach capacity c
      cost += prices[u.node];
      int& bcost = d[u.node][f];
      if(bcost > cost) {
        bcost = cost;
        pq.push(State(u.node, f, cost));
      }
    }*/

    FOREACH(el, g[u.node]) {
      if(el->second <= u.fuel) {
        int nfuel = u.fuel - el->second;
        if(u.cost < d[el->first][nfuel]) {
          d[el->first][nfuel] = u.cost;
          pq.push(State(el->first, nfuel, u.cost));
        }
      } else if(u.fuel < c) {
        int cost = u.cost + prices[u.node];
        int& bcost = d[u.node][u.fuel+1];
        if(bcost > cost) {
          bcost = cost;
          pq.push(State(u.node, u.fuel+1, cost));
        }
      }
    }
  }

  return INF;
}
Example #26
0
int main(){
    ll n,r,avg;
    cin>>n>>r>>avg;
    ll totgn=0,need=n*avg;
    for(int i=0;i<n;++i)cin>>a[i]>>b[i],totgn+=a[i],pq.push({b[i],r-a[i]});
    ll ans=0;
    while(totgn<need){
        // PDE2(pq.top().es,pq.top().lft);
        if(pq.top().lft>=need-totgn){
            ans+=pq.top().es*(need-totgn);
            break;
        }
        ans+=pq.top().es*pq.top().lft;
        totgn+=pq.top().lft;
        pq.pop();
    } cout<<ans<<endl;
}
Example #27
0
// find top-k CCs using vectors graph representation
PQ find_top_CC2(vector<vector<int> >& PW, int V, int k) {

	PQ pq; // priority queue for top-k CC
	map<int, bool> explored;
	for (int i = 0; i < V; ++i)
		explored[i] = false;
	int cc_number = 0;
	int unit_sized = 0;

	for (int i = 0; i < V; ++i) {
		if (!explored[i]) {
			// perform BFS for vertex i
			vector<int> CC;
			CC.push_back(i);
			explored[i] = true;
			vector<int>::size_type ix = 0;
			while (ix < CC.size()) {
				int pw_size = PW[CC[ix]].size();
				for (int j = 0; j < pw_size; ++j) {
					int v = PW[CC[ix]][j];
					if (!explored[v]) {
						CC.push_back(v);
						explored[v] = true;
					}
				}
				ix++;
			}
//			if (CC.size() > 5)
//				cout << cc_number << ": " << CC.size() << endl;
			if (CC.size() == 1) {
				unit_sized++;
			}
			cc_number++;

			// maintain CC priority queue
			int pq_size = pq.size();
			if (pq_size == k) {
				vector<int> top = pq.top();
				if (top.size() < CC.size()) {
					pq.pop();
					pq.push(CC);
				}
			}
			else
				pq.push(CC);
		}
	}
//	cout << "Total CCs: " << cc_number << endl;
//	cout << "Unit CCs: " << unit_sized << endl;
	return pq;
}
int main()
{
    int numbers;
    int num;
    PQ myPQ;
    int sum;
    int totalCost;

    while (scanf("%d", &numbers) && numbers != 0)
    {
        totalCost = 0;

        for (int i = 0; i < numbers; i++)
        {
            scanf("%d", &num);
            myPQ.push(num);
        }

        while (true)
        {
            sum = myPQ.top();
            myPQ.pop();
            sum += myPQ.top();
            myPQ.pop();
            totalCost += sum;

            if (!myPQ.empty())
                myPQ.push(sum);
            else
                break;
        }

        printf("%d\n", totalCost);
    }

    return 0;
}
Example #29
0
void
pq_insert(PQ pq, const void *elt)
{
    int floater;                /* new element */

    while(pq->n + 1 > pq->size) {
        pq->size *= 2;
        pq->data = realloc(pq->data, pq->element_length * pq->size);
        assert(pq->data);
    }

    /* copy the new element in */
    floater = pq->n++;
    memcpy(REF(pq, floater), elt, pq->element_length);

    /* float it up until it is at the top */
    /* or it is no smaller than its parent */
    while(floater > 0 && pq->compare(REF(pq, floater), REF(pq, Parent(floater))) <= 0) {
        /* it's smaller than its parent */
        pq_swap(pq, floater, Parent(floater));
        floater = Parent(floater);
    }
}
Example #30
0
void dfs(int rt, int fa)
{
     vis[rt] = true;
     if (adj[rt].size() == 1 && adj[rt][0] == fa) {f[rt].pb(v[rt]); return;}
     PQ q;
     q.push(v[rt]);
     for (int i=0; i<adj[rt].size(); i++)
     {
         int id = adj[rt][i];
         if (!vis[id] && id != fa) {dfs(id, rt);
         for (int j=0; j<f[id].size(); j++) q.push(f[id][j]);}
     }
     int cnt = 0;
     while (!q.empty() && cnt < 3)
     {
        f[rt].pb(q.top());
        q.pop();
        cnt++;           
     }
     sort(f[rt].begin(), f[rt].end(), greater<int>());
     return ;     
     }