/** Initialize your data structure here. */
struct MedianFinder* MedianFinderCreate() {
  struct MedianFinder *mf = ( struct MedianFinder *)malloc(sizeof( struct MedianFinder));
  mf->minheap = createHeap(100);
  mf->maxheap = createHeap(100);
  mf->median=0.0;
  return mf;
}
Beispiel #2
0
void slove()
{
    int n, e,e1,e2;
    long long cost;
    //priority_queue< int, vector<int>, greater<int> >que;
    Heap *H;
    scanf("%d", &n);
    H= createHeap(n);
    
    while(n--)
    {
        scanf("%d",&e);
        //que.push(e);
        pushHeap(H,e);
    }
    cost = 0;
    //while(que.size() > 1)
    while(H->size > 1)
    {
//        e1 = que.top(),que.pop();
//        e2 = que.top(),que.pop();
        e1 = popHeap(H);
        e2 = popHeap(H);
        
        cost += e1 + e2;
        //que.push(e1+e2);
        pushHeap(H,e1+e2);
    }
    printf("%lld\n", cost);
    destoryHeap(H);
}
Beispiel #3
0
int main()
{
	int n, j;
	scanf("%d",&n);
	heap *test_heap=createHeap(n);
	for(j=0; j<n; j++)
		scanf("%d",(test_heap->arr)+j);

	//builds max heap of the array and sets heapsize to len-1
	buildmaxheap(test_heap);
//	heapsort(test_heap);
	/*printf("\n%d",HeapExtractMax(test_heap));
	printf("\n%d",HeapExtractMax(test_heap));
	printf("\n%d",HeapExtractMax(test_heap));
	printf("\n%d",HeapExtractMax(test_heap));*/

	printHeap(test_heap);
	printf("\nIncrease key");
	HeapIncreaseKey(test_heap,4,18);
	printHeap(test_heap);

	printf("\nInsert key");
	MaxHeapInsert(test_heap,20);
	printHeap(test_heap);
	MaxHeapInsert(test_heap,-5);
	printHeap(test_heap);
	MaxHeapInsert(test_heap,10);
	printHeap(test_heap);
	
	printf("\n");
	free(test_heap->arr);	
	free(test_heap);
	return 0;
}
Beispiel #4
0
struct ListNode* sortList(struct ListNode* head) {
    int c = 0;
    struct ListNode* cur = head;
    while (cur) {
        c++;
        cur = cur->next;
    }
    
    int num[c];
    cur = head;
    c = 0;
    while (cur) {
        num[c++] = cur->val;
        cur = cur->next;
    }
    createHeap(num, c);
    
    cur = head;
    while (cur) {
        cur->val = heapSort(num, 0, c);
        num[0] = num[--c];
        cur = cur->next;
    }
    return head;
}
Beispiel #5
0
void mergeKSortedArrays1(int arr1[][n], int k)
{
  maxheap *h = createHeap(k);
  h->nodes = (HeapNode**)malloc(sizeof(HeapNode*)*k);
  int i=0, j=0, m=0, idx=0;
  int *output = (int *)malloc(sizeof(int)*n*k);
  for(i=0;i<k;i++)
  {
    insertHeapObj(h,arr1[i][0],1,i);
  }
  for(j=0;j<n*k;j++)
  {
    HeapNode *tmp= extractMinObj(h);
    output[j] = tmp->elem;
    if(tmp->nxt_idx<n)
    {
      m=tmp->nxt_idx;
      idx= tmp->arr_idx;
      insertHeapObj(h, arr1[idx][m],m+1,idx);
    }
  }
  for(i=0;i<n*k;i++)
  {
    printf("%d ,", output[i]);
  }
  if(output)
    free(output);
  if(h)
    free(h);
}
Beispiel #6
0
void heapSort(int *a, int num)
{
    createHeap(a, num);
    int i;
    for(i=num-1; i>=0; i--)
    {
        swap(a+i, a);
        heapify(a, i, 0);
    }
}
Beispiel #7
0
void astarRun() {

    int map[20][20] =
    {
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,3,0,0,3,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,3,0,0,3,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,3,0,0,3,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,3,0,0,3,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0},
    };
    int in_open[20][20] ={0};

    Star begin_star ={0,0,0,0,0};
    Star end_star = {19,19,0,0,0};

    Heap *open_heap;
    Star star[300];
    createHeap(open_heap,star,0,min_heap_compare);
    find_path(begin_star,end_star,map,open_heap,in_open);
    printHeap(open_heap);

    for (int i=0;i<20;i++) {
	for(int j=0;j<20;j++) {
	    if (map[i][j]==0){
		putchar('-');
		putchar(' ');
	    }
	    else if(map[i][j] ==1){
		putchar('o');
		putchar(' ');
	    }else
	    {
		putchar('#');
		putchar(' ');
	    }
	}
	putchar('\n');
    }
}
	void configure(){
		setLoggingLevelEnabled(LOGGING_LEVEL_DEBUG);
		setVdaRunningStatus(TRUE);
		setGlobalHeap( createHeap(1024) );
		setupConfiguration();
		if (!isVdaOfflineMode()) {
			initializeWinsock();
			initializeKssConnection();
		}
		if(isVdaAvailableCache())
			initializeCache();
		initializeDisk();
	}
Beispiel #9
0
Set 
*dijkstra(Graph *g, Label v, int Home, int n) {
	// for the school vertex v, find all indices for homes and put all into
	// a set
	Heap *H;
	Edge *Eu;
	Set *S;
	int i, usize;
	Label u;
	float R[n], delta;
	// create a heap to store the distance for every vertices
	// and an array to store dist values
	H = createHeap();
	for (i=0;i<n;i++) {
		if (i==v) {
			insert(H, i, 0);
			R[i]=0;
			continue;
		}
		insert(H, i, INFINITY);
		R[i] = INFINITY;
	}
	// then loop through the heap
	while (H->n) {
		// extract the min in the heap
		u = removeMin(H);
		// if dist of u exceeds 1km, stop the loop
		if (R[u]>1000) {
			break;
		}
		Eu = graph_get_edge_array(g, u, &usize);
		for (i=0;i<usize;i++) {
			if (R[Eu[i].u]>R[u]+ *(float*)(Eu[i].data)) {
				delta = R[u] + *(float*)(Eu[i].data) - R[Eu[i].u];
				changeKey(H, Eu[i].u, delta);
				R[Eu[i].u] = R[u]+ *(float*)(Eu[i].data);
			}
		}
	}
	// now add all home indices with in the range of 1km into the set
	S = set_new();
	for (i=0;i<Home;i++) {
		if (R[i]<=1000) {
			set_add(S, i);
		}
	}
	return S;
}
Beispiel #10
0
// An implementation of brute k-NN search that uses a heap.
void bruteKHeap(matrix X, matrix Q, unint **NNs, float **dToNNs, unint K) {
    float temp[CL];
    int i, j, k,t;

    int nt = omp_get_max_threads();
    heap **hp;
    hp = (heap**)calloc(nt, sizeof(*hp));
    for(i=0; i<nt; i++) {
        hp[i] = (heap*)calloc(CL, sizeof(**hp));
        for(j=0; j<CL; j++)
            createHeap(&hp[i][j],K);
    }

    #pragma omp parallel for private(t,k,j,temp)
    for( i=0; i<Q.pr/CL; i++ ) {
        t = i*CL;
        unint tn = omp_get_thread_num();
        heapEl newEl;

        for(j=0; j<X.r; j++ ) {
            for(k=0; k<CL; k++) {
                //temp[k] = distVec( Q, X, t+k, j );
                temp[k] = distVecLB( Q, X, t+k, j, hp[tn][k].h[0].val );
            }
            for(k=0; k<CL; k++) {
                if( temp[k] <= hp[tn][k].h[0].val ) {
                    newEl.id=j;
                    newEl.val=temp[k];
                    replaceMax( &hp[tn][k], newEl);
                }
            }
        }
        for(j=0; j<CL; j++)
            if(t+j<Q.r)
                heapSort(&hp[tn][j], NNs[t+j], dToNNs[t+j]);

        for(j=0; j<CL; j++)
            reInitHeap(&hp[tn][j]);
    }

    for(i=0; i<nt; i++) {
        for(j=0; j<CL; j++)
            destroyHeap(&hp[i][j]);
        free(hp[i]);
    }
    free(hp);
}
Beispiel #11
0
int main(){
	heap* h=NULL;
	h=createHeap(15,-1);
	int A[]={3,5,1,8,19,10,6,2,11,53};
	//printf("%d, %d",h->capacity, h->type);
	//buildHeap(h,A,10);
	insert(h,24);
	insert(h,111);
	insert(h,32);
	insert(h,511);
	//printf("max: %d",deleteType(h));
	//printf("max: %d",deleteType(h));
	printf("after sorting");
	heapSort(h);
	int i; scanf("%d",&i);
return 0;
}
Beispiel #12
0
// Returns residue based on Karmarkar-Karp algorithm for array nums of length n
uint64_t kk(uint64_t* nums, int n) {
    // Initialize heap
    heap* h = createHeap(n);
    for (int i = 0; i < n; i++) {
        insert(h, nums[i]);
    }

    // Run algorithm
    while (getSize(h) > 1) {
        insert(h, pop(h) - pop(h));
    }

    // Return final element
    uint64_t residue = pop(h);
    freeHeap(h);
    return residue;
}
Beispiel #13
0
void mergeKSortedArrays(int arr1[][n], int k)
{
    maxheap *h = createHeap(13);
    int *output = (int *)malloc(sizeof(int)*n*k);
    int i=0, j=0;
    for(i=0;i<n;i++)
    {
      for(j=0;j<k;j++)
      {
	  insertMinHeap(h,arr1[j][i]); 
      }
    }
    for(i=0;i<n*k;i++)
    {
      output[i]=extractMin(h);
      printf("%d ,", output[i]);
    }
}
Beispiel #14
0
heap* getData(char *file){
	FILE* input_file = fopen(file,"r");
	if(input_file == NULL){
		printf("Error opening input file %s\n",file);
		exit(1);
	}
	float inputx = 0.0;
	float inputy = 0.0;	
	heap *newheap = createHeap();
	int i = 0;
	while(fscanf(input_file, "%f", &inputx) != EOF){
		fscanf(input_file, "%f", &inputy);
		data *d= createData(inputx,inputy);
		d->distance = calculateDistance(d->valx,d->valy);
		if(i>9){
			if(d->distance < newheap->root->d->distance){
				leaf *removeleaf = removeRoot(newheap);
#if DEBUG
				printf("deleted : %f and inserted : %f -- \n",removeleaf->d->distance,d->distance);
#endif
				popBack(newheap->q->ll);
				free(removeleaf->d);
				free(removeleaf);
				addLeaf(newheap,d);
			} else {
#if DEBUG			
				printf("Skipped : %f => ",d->distance);
				printf("deleting ...... \n");
#endif
				free(d);
			}
		}
		else { 	
#if DEBUG		
			printf("inserted : %f -- \n",d->distance);
#endif
			addLeaf(newheap,d);
		}
		i++;
	}
	
	fclose(input_file);
	return newheap;
}
Beispiel #15
0
void encode (char *name, BYTE *data, int len)
{
    strcat(name, ".hf");
    
    FILE *fil = fopen(name, "wb");
    fwrite(&len, 1, 4, fil);
    if (len)
    {
        BYTE *p = data;
        for (int i=0; i < len; i++)
        {
            freqs[*p++].freq ++;
        }
        int count = createHeap();
        HUFF * result = NULL;
        while (1)
        {
            result = BHeapRemove(heap);
//            printf("removing '%c'",result->ch);
            HUFF *result1 = BHeapRemove(heap);
            if (!result1)
            {
//                printf("\n");
                break;
            }
//            printf(":'%c'\n",result1->ch);
            HUFF * nw = calloc(sizeof(HUFF), 1);
            nw->ch = -1;
            nw->freq = result->freq + result1->freq;
            nw->children[0] = result;
            nw->children[1] = result1;
            result->parent = nw;
            result1->parent = nw;
            BHeapInsert(heap, nw);
        }
        encodeTree(fil, result);
        p = data;
        for (int i=0 ; i < len; i++)
            encodeSymbol(fil, &freqs[*p++]);
        flush(fil);
    }
    fclose(fil);
}
Beispiel #16
0
int main() 
{
	ElemType arr[] = {1, 7, 5, 3, 8, 6, 15, 13, 14};
	int i, n = sizeof(arr)/sizeof(arr[0]);

	pHeapHeader pHH = (pHeapHeader)malloc(sizeof(struct HeapHeader));
	initHeap(pHH, n);
    createHeap(pHH, arr, n);	

	InsertHeap(pHH, 10);
	for(i=0; i<pHH->currentSize; i++) {
		printf("%d\t", (pHH->point)[i]);
	}
	printf("\nMaxHeap value: %d\n", RemoveMax(pHH));
	for(i=0; i<pHH->currentSize; i++) {
		printf("%d\t", (pHH->point)[i]);
	}



	return 0;
}
int main() {
	int i;
	srand(time(NULL));
	Heap * h = createHeap(100);
	for (i = 0; i < 100; ++i) {
		if (i > 20) {
			heapAdd(h, createHeapNode(FLT_MAX, i));
			continue;
		}
		heapAdd(h, createHeapNode(rand() % 100, i));
	}

	displayHeap(h);
	for (i = 0; i < 10; ++i) {
		HeapNode *tmp = heapExtractHead(h);

		fprintf(stdout, "\nAncien noeud : ");
		displayHeapNode(tmp);
		fprintf(stdout, "\n");
		tmp->c = rand() * i % 100 + 100;
		fprintf(stdout, "Nouveau noeud : ");
		displayHeapNode(tmp);

		heapAdd(h, tmp);

		displayHeap(h);
	}

	HeapNode * tmp = heapExtract(h, 2);
	tmp->c = rand() % 100;

	heapAdd(h, tmp);

	displayHeap(h);

	freeHeap(h);

	return 0;
}
int calculateMoves(int LadderArr[],int SnakeArr[],int board[],int nL, int nS)
{

		/*create a graph*/
		/*each vertex is from the LadderArr[], including a 1 and 100 */
		/*mark the board array with ladder elements */
		/* sort the ladder array */
		/* when adding a vertex, add path to all elements greater than the vertex */
		/* keep moving till ladder Arr is finished */
		int i;
		graph* gr;
		heap* h;
		float moves;
		int size=0;
		float *vert;

		LadderArr[2*nL]=1;
		LadderArr[2*nL+1]=100;
		nL=2*nL+2;

		qsort(LadderArr,nL,sizeof(int),cmpfunc);
#ifdef DEBUG
		for(i=0;i<nL;i++)
		{
			printf("%d ",LadderArr[i]);
		}
#endif		
		gr=makeGraphFromArray(LadderArr,nL,board);
		h= createHeap(gr,1,&size);
		h->size=size;
		vert=(float*)calloc(gr->num,sizeof(float));
		moves=getShortestPathUtil(gr,h,vert,100);
		
		return moves;

}
Beispiel #19
0
void prepare (int len)

  { int i,id;
    Tpair pair;
    c = u = len;

    INI_c = c;  //fari... para mostrar numero de iteracion y progreso durante repair (mejora por cada nueva regla)
    
    alph = 0;
    for (i=0;i<u;i++) 
	{ if (C[i] > alph) alph = C[i];
	}
    n = ++alph;
    Rec = createRecords(factor,minsize);
    Heap = createHeap(u,&Rec,factor,minsize);
    Hash = createHash(256*256,&Rec);
    L = (void*)malloc(u*sizeof(Tlist));
    assocRecords (&Rec,&Hash,&Heap,L);
    for (i=0;i<c-1;i++) 
	{ pair.left = C[i]; pair.right = C[i+1];
	  id = searchHash (Hash,pair);
    	  if (id == -1) // new pair, insert
	     { id = insertRecord (&Rec,pair);
	       L[i].next = -1;
	     }
	  else 
	     { L[i].next = Rec.records[id].cpos;
	       L[L[i].next].prev = i;
	       incFreq (&Heap,id);
	     }
	  L[i].prev = -id-1;
	  Rec.records[id].cpos = i;
if (PRNL && (i%10000 == 0)) printf ("Processed %i chars\n",i);
	}
    purgeHeap (&Heap);
  }
Beispiel #20
0
//Exact k-NN search with the RBC
void searchExactK(matrix q, matrix x, matrix r, rep *ri, unint **NNs, real **dNNs, unint K){
  unint i, j, k;
  unint *repID = (unint*)calloc(q.pr, sizeof(*repID));
  real **dToReps = (real**)calloc(q.pr, sizeof(*dToReps));
  for(i=0; i<q.pr; i++)
    dToReps[i] = (real*)calloc(K, sizeof(**dToReps));
  intList *toSearch = (intList*)calloc(r.pr, sizeof(*toSearch));
  for(i=0;i<r.pr;i++)
    createList(&toSearch[i]);
  int nt = omp_get_max_threads();

  float ***d;  //d is indexed by: thread, cache line #, rep #
  d = (float***)calloc(nt, sizeof(*d));
  for(i=0; i<nt; i++){
    d[i] = (float**)calloc(CL, sizeof(**d));
    for(j=0; j<CL; j++){
      d[i][j] = (float*)calloc(r.pr, sizeof(***d));
    }
  }
  
  heap **hp;
  hp = (heap**)calloc(nt, sizeof(*hp));
  for(i=0; i<nt; i++){
    hp[i] = (heap*)calloc(CL, sizeof(**hp));
    for(j=0; j<CL; j++)
      createHeap(&hp[i][j],K);
  }
  
#pragma omp parallel for private(j,k)
  for(i=0; i<q.pr/CL; i++){
    unint row = i*CL;
    unint tn = omp_get_thread_num();
    heapEl newEl; 

    for( j=0; j<r.r; j++ ){
      for(k=0; k<CL; k++){
	d[tn][k][j] = distVec(q, r, row+k, j);
	if( d[tn][k][j] < hp[tn][k].h[0].val ){
	  newEl.id = j;
	  newEl.val = d[tn][k][j];
	  replaceMax( &hp[tn][k], newEl );
	}
      }
    }
    for(j=0; j<r.r; j++ ){
      for(k=0; k<CL; k++ ){
	real minDist = hp[tn][k].h[0].val;
	real temp = d[tn][k][j];
	if( row + k<q.r && minDist >= temp - ri[j].radius && 3.0*minDist >= temp ){
#pragma omp critical
	  {
	    addToList(&toSearch[j], row+k);
	  }
	}
      }
    }
    for(j=0; j<CL; j++)
      reInitHeap(&hp[tn][j]);
  }

  for(i=0; i<r.r; i++){
    while(toSearch[i].len % CL != 0)
      addToList(&toSearch[i],DUMMY_IDX);
  }

  bruteListK(x,q,ri,toSearch,r.r,NNs,dNNs,K);

  
  //clean-up
  for(i=0; i<nt; i++){
    for(j=0; j<CL; j++)
      destroyHeap(&hp[i][j]);
    free(hp[i]);
  }
  free(hp);
  for(i=0;i<r.pr;i++)
    destroyList(&toSearch[i]);
  free(toSearch);
  free(repID);
  for(i=0;i<q.pr; i++)
    free(dToReps[i]);
  free(dToReps);
  for(i=0; i<nt; i++){
    for(j=0; j<CL; j++)
      free(d[i][j]); 
    free(d[i]);
  }
  free(d);
}
void setCover(Universe *Uni,int num_houses) {



	Heap *Q = createHeap();

	set_t *covered = create_set(num_houses);
	

	for(int i=0;i<Uni->size_of_universe;i++) {
		insert_in_heap(Q,i,Uni->sets[i].covered_items,max_func);
	}

	
 
	while(covered->covered_items < num_houses) {

		
		if(isEmpty(Q)) {
			break;
		}

		HeapItem max = removeTop(Q,max_func);
		

		
		//updating the covered set
		for(int i=0;i<Uni->sets[max.dataIndex].covered_items;i++) {

			//if its not covered 
			if(!covered->set[Uni->sets[max.dataIndex].set[i]]) {
					//set to the house being covered 
					covered->set[Uni->sets[max.dataIndex].set[i]] = 1;
					//increment number of covered houses
					covered->covered_items++;
			}
		}
	
		//flag the current set to be covered 
		Uni->sets[max.dataIndex].covered = 1;
				
 		//update the other sets
		for(int i=0;i<Uni->size_of_universe;i++) {

				//if they are not already covered
				if(!Uni->sets[i].covered) {

					//find set diff and update the heap
					int diff = set_diff(&Uni->sets[i],covered);
					changeKey(Q,i,diff,max_func);
				}
				
		}
		
	}

	if(covered->covered_items < num_houses) {
		fprintf(stderr, "Not enough houses to cover all houses.\n");
		exit(EXIT_FAILURE);
	}
	
	for(int i=0; i<Uni->size_of_universe;i++) {
		if(Uni->sets[i].covered) {
			printf("%d\n",i);
		}
	}


	destroyHeap(Q);
	free_set(covered);
	free_Universe(Uni);


}
void Dijkstra(Graph *g,int source,Universe *Uni,int (cmp)(int,int)) {

    int *dist;

    dist = (int*)malloc(sizeof(int)*(g->number_of_vertices));
    assert(dist);
   
    //set all vertices distance to INF
    for(int i=0;i<g->number_of_vertices;i++) {
        dist[i] = INF;
    }



    Heap *Q = createHeap();
    //insert everything into heap
    for(int i=0;i<g->number_of_vertices;i++) {

        if(i==source) {
            insert_in_heap(Q,i,0,cmp);
        }
        else {
            insert_in_heap(Q,i,INF,cmp);
        }
    }
    // update the distance of source 
    dist[source] = 0;
    
 

    while(!isEmpty(Q)) {


       
        HeapItem min  = removeTop(Q,cmp);

        // min can't be > 1000, if so we can stop
         if(min.key > MAX_KM) {
            break;
        }
        // prune any schools, only houses
        if(min.dataIndex < g->num_houses) {
            insert(Uni, source-g->num_houses, min.dataIndex);
        }       

        int n_edges;
        //get all edges from min.dataIndex
        Edge *edges = graph_get_edge_array(g,min.dataIndex,&n_edges);
       



        for(int i=0;i<n_edges;i++) {

        	//update all the edges distances if there is a minimum 
            if(dist[edges[i].u] > (dist[min.dataIndex] +edges[i].weight)) {
                
                dist[edges[i].u] = dist[min.dataIndex]+edges[i].weight;
                // update the heap
                changeKey(Q,edges[i].u,dist[edges[i].u],cmp);
                                
            }

        }
    
    }

    
}
Beispiel #23
0
// Performs a brute force K-NN search, but only between queries and points
// belonging to each query's nearest representative.  This method is used by
// the one-shot algorithm.
void bruteMapK(matrix X, matrix Q, rep *ri, unint* qMap, unint **NNs, float **dToNNs, unint K) {
    unint i, j, k;

    //Sort the queries, so that queries matched to a particular representative
    //will be processed together, improving cache performance.
    size_t *qSort = (size_t*)calloc(Q.pr, sizeof(*qSort));
    gsl_sort_uint_index(qSort,qMap,1,Q.r);

    unint nt = omp_get_max_threads();

    heap **hp;
    hp = (heap**)calloc(nt, sizeof(*hp));
    for(i=0; i<nt; i++) {
        hp[i] = (heap*)calloc(CL, sizeof(**hp));
        for(j=0; j<CL; j++)
            createHeap(&hp[i][j],K);
    }


    #pragma omp parallel for private(j,k) schedule(static)
    for( i=0; i<Q.pr/CL; i++ ) {
        unint row = i*CL;
        unint tn = omp_get_thread_num();
        heapEl newEl;

        float temp[CL];
        rep rt[CL];
        unint maxLen = 0;
        for(j=0; j<CL; j++) {
            rt[j] = ri[qMap[qSort[row+j]]];
            maxLen = MAX(maxLen, rt[j].len);
            temp[j]=0.0; //gets rid of compiler warning
        }

        for(j=0; j<maxLen; j++ ) {
            for(k=0; k<CL; k++ ) {
                if( j<rt[k].len )
                    temp[k] = distVecLB( Q, X, qSort[row+k], rt[k].lr[j], hp[tn][k].h[0].val  );
            }

            for(k=0; k<CL; k++ ) {
                if( j<rt[k].len ) {
                    if( temp[k] < hp[tn][k].h[0].val ) {
                        newEl.id = rt[k].lr[j];
                        newEl.val = temp[k];
                        replaceMax( &hp[tn][k], newEl );
                    }
                }
            }
        }

        for(j=0; j<CL; j++)
            heapSort( &hp[tn][j], NNs[qSort[row+j]], dToNNs[qSort[row+j]] );

        for(j=0; j<CL; j++)
            reInitHeap(&hp[tn][j]);
    }

    for(i=0; i<nt; i++) {
        for(j=0; j<CL; j++)
            destroyHeap(&hp[i][j]);
        free(hp[i]);
    }
    free(hp);
    free(qSort);
}
Beispiel #24
0
// This method is the same as the above bruteList method, but for k-nn search.
// It uses a heap.
void bruteListK(matrix X, matrix Q, rep *ri, intList *toSearch, unint numReps, unint **NNs, float **dToNNs, unint K) {
    float temp;
    unint i, j, k, l;

    unint nt = omp_get_max_threads();
    unint m = Q.r;

    heap **hp;
    hp = (heap**)calloc(nt, sizeof(*hp));
    for(i=0; i<nt; i++) {
        hp[i] = (heap*)calloc(m, sizeof(**hp));
        for(j=0; j<m; j++)
            createHeap(&hp[i][j],K);
    }

    #pragma omp parallel for private(j,k,l,temp)
    for( i=0; i<numReps; i++ ) {
        unint tn = omp_get_thread_num();
        heapEl newEl;

        for( j=0; j< toSearch[i].len/CL; j++) { //toSearch is assumed to be padded
            unint row = j*CL;
            unint qInd[CL];
            for(k=0; k<CL; k++)
                qInd[k] = toSearch[i].x[row+k];
            rep rt = ri[i];
            for(k=0; k<rt.len; k++) {
                for(l=0; l<CL; l++ ) {
                    if(qInd[l]!=DUMMY_IDX) {
                        temp = distVecLB( Q, X, qInd[l], rt.lr[k], hp[tn][qInd[l]].h[0].val );
                        if( temp < hp[tn][qInd[l]].h[0].val ) {
                            newEl.id = rt.lr[k];
                            newEl.val = temp;
                            replaceMax( &hp[tn][qInd[l]], newEl );
                        }
                    }
                }
            }
        }
    }

    // Now merge the NNs found by each thread.  Currently this performs the
    // merge within one thread, but should eventually be done in a proper
    // parallel-reduce fashion.
    unint **tInds;
    float **tVals;
    tInds = (unint**)calloc(nt, sizeof(*tInds));
    tVals = (float**)calloc(nt, sizeof(*tVals));
    for( i=0; i<nt; i++ ) {
        tInds[i] = (unint*)calloc(K, sizeof(**tInds) );
        tVals[i] = (float*)calloc(K, sizeof(**tVals) );
    }

    size_t *indVec = (size_t*)calloc(nt*K, sizeof(*indVec));
    size_t *tempInds = (size_t*)calloc(nt*K, sizeof(*tempInds));
    float *valVec = (float*)calloc(nt*K, sizeof(*valVec));

    for( i=0; i<m; i++) {

        for( j=0; j<nt; j++) {
            heapSort( &hp[j][i], tInds[j], tVals[j] );
            for( k=0; k<K; k++) {
                indVec[j*K + k] = tInds[j][k];
                valVec[j*K + k] = tVals[j][k];
            }
        }

        gsl_sort_float_index(tempInds, valVec, 1, nt*K);
        for( j=0; j<K; j++ ) {
            dToNNs[i][j] = valVec[tempInds[j]];
            NNs[i][j] = indVec[tempInds[j]];
        }
    }

    free(tempInds);
    free(indVec);
    free(valVec);
    for( i=0; i<nt; i++ ) {
        free(tInds[i]);
        free(tVals[i]);
    }
    free(tInds);
    free(tVals);
    for(i=0; i<nt; i++) {
        for(j=0; j<m; j++)
            destroyHeap(&hp[i][j]);
        free(hp[i]);
    }
    free(hp);
}