Ejemplo n.º 1
0
int solution(int A[], int N) {
    // write your code in C99 (gcc 4.8.2)
    int* result=(int*)malloc(sizeof(int)*N);
    int answer=0;
    buildHeap(A,N);
    for(int i=0;i<N;i++)
    {
    result[i]=extractMax(A,N-i);    
    }
    for(int i=0;i<N;i++)
    {
     if(i==0){
        answer++;    
     }
     else{
        if(result[i]!=result[i-1])
        {
        answer++;    
        }
         
     }
        
    }
    return answer;
}
Ejemplo n.º 2
0
int main(){
	init();
	
	int i, newkey, key;
	for(i=0; i<9; i++){
	scanf("%d", &newkey);
	insert(newkey, queue);
	}
	key = extractMax(omega);
	printf("%d ", key);
return 0;
}
 // Adds a number into the data structure.
 void addNum(int num) {
     if(maxHeap.size() == 0 && minHeap.size() == 0) {
         maxHeap.push_back(num);
         return;
     }// if first num to add
     if(maxHeap.size() <= minHeap.size()){
         if(num > minHeap[0]){
             minHeap.push_back(num);
             minHeapify();
             maxHeap.push_back(extractMin());
             maxHeapify();
             //return;
         }else{
             maxHeap.push_back(num);
             maxHeapify();
             //return;
         }
     }else{
         if(num < maxHeap[0]){
             maxHeap.push_back(num);
             maxHeapify();
             minHeap.push_back(extractMax());
             minHeapify();
             //return;
         }else{
             minHeap.push_back(num);
             minHeapify();
             //return;
         }
     }
     if(maxHeap.size()>minHeap.size() + 1){
         minHeap.push_back(extractMax());
         minHeapify();
     }else if(minHeap.size()>maxHeap.size()){
         maxHeap.push_back(extractMin());
         maxHeapify();
     }
 }
Ejemplo n.º 4
0
int main(){
	insert(5);
	insert(7);
	insert(3);
	insert(8);
	insert(12);
	insert(14);
	insert(118);
	print_queue();
	
	printf("\nextractMax:\n");
	int max = extractMax();		
	printf("\nThe Max is %d.\n",max);
	print_queue();
	
	printf("\nincrease, index is [5] and value is [10]:\n");
	increase(5,10);
	print_queue();
	
	printf("\nChange value, index is [5] and value is [10]:\n");
	change(5,10);
	print_queue();
	return 0;
}
Ejemplo n.º 5
0
// Fari:
// Posto que alpha = num_terminais = valor do primeiro non-terminal.
//  ** a primeira regla sería: alpha <-- left1,right1
//  ** a  segunda regla sería: alpha +1 <-- left2, right2
// por iso no ficheiro de reglas só garda <alpha> e despois: left1, right1, left2, right2,... 
// pois xa sabe que os valores alpha, alpha+1,... son contiguos ;)
int repair (FILE *R)

  { int oid,id,cpos;
    Trecord *rec,*orec;
    Tpair pair;
    if (fwrite(&alph,sizeof(int),1,R) != 1) return -1;
if (PRNC) prnC();

int i=0;  //fari... solo para mostrar numero de iteracion
double prev_ratio =100.0;

while (n+1 > 0)
{ 
	if (PRNR) prnRec();
		oid = extractMax(&Heap);
		if (oid == -1) break; // the end!!
		orec = &Rec.records[oid];
		cpos = orec->cpos;
		if (fwrite (&orec->pair,sizeof(Tpair),1,R) != 1) return -1;
	if (PRNP) 
		{ printf("Chosen pair %i = (",n);
		  prnSym(orec->pair.left);
		  printf(",");
		  prnSym(orec->pair.right);
		  printf(") (%i occs)\n",orec->freq);
		}
	while (cpos != -1)
	   { int ant,sgte,ssgte; 
		// replacing bc->e in abcd, b = cpos, c = sgte, d = ssgte
	     if (C[cpos+1] < 0) sgte = -C[cpos+1]-1; 
	     else sgte = cpos+1; 
	     if ((sgte+1 < u) && (C[sgte+1] < 0)) ssgte = -C[sgte+1]-1;
	     else ssgte = sgte+1; 
		// remove bc from L
	     if (L[cpos].next != -1) L[L[cpos].next].prev = -oid-1;
	     orec->cpos = L[cpos].next;
	     if (ssgte != u) // there is ssgte
		{ 	// remove occ of cd
		  pair.left = C[sgte]; pair.right = C[ssgte];
		  id = searchHash(Hash,pair);
		  if (id != -1) // may not exist if purgeHeap'd
	             { if (id != oid) decFreq (&Heap,id); // not to my pair!
		       if (L[sgte].prev != NullFreq) //still exists(not removed)
 		          { rec = &Rec.records[id];
		            if (L[sgte].prev < 0) // this cd is head of its list
		               rec->cpos = L[sgte].next;
		            else L[L[sgte].prev].next = L[sgte].next;
		            if (L[sgte].next != -1) // not tail of its list
		               L[L[sgte].next].prev = L[sgte].prev;
			  }
		     }
			// create occ of ed
	          pair.left = n;
		  id = searchHash(Hash,pair);
	          if (id == -1) // new pair, insert
		     { id = insertRecord (&Rec,pair);
 		       rec = &Rec.records[id];
	               L[cpos].next = -1;
		     }
	          else 
 		     { incFreq (&Heap,id);
 		       rec = &Rec.records[id]; 
	               L[cpos].next = rec->cpos;
	               L[L[cpos].next].prev = cpos;
	             }
	          L[cpos].prev = -id-1;
	          rec->cpos = cpos;
		}
	     if (cpos != 0) // there is ant
		{ 	// remove occ of ab
	          if (C[cpos-1] < 0) 
		     { ant = -C[cpos-1]-1; 
		       if (ant == cpos) // sgte and ant clashed -> 1 hole
			  ant = cpos-2;
		     }
	          else ant = cpos-1; 
		  pair.left = C[ant]; pair.right = C[cpos];
		  id = searchHash(Hash,pair);
		  if (id != -1) // may not exist if purgeHeap'd
	             { if (id != oid) decFreq (&Heap,id); // not to my pair!
		       if (L[ant].prev != NullFreq) //still exists (not removed)
 		          { rec = &Rec.records[id];
		            if (L[ant].prev < 0) // this ab is head of its list
		                 rec->cpos = L[ant].next;
		            else L[L[ant].prev].next = L[ant].next;
		            if (L[ant].next != -1) // it is not tail of its list
		               L[L[ant].next].prev = L[ant].prev;
			  }
		     }
			// create occ of ae
	          pair.right = n;
		  id = searchHash(Hash,pair);
	          if (id == -1) // new pair, insert
		     { id = insertRecord(&Rec,pair);
 		       rec = &Rec.records[id];
	               L[ant].next = -1;
	             }
	          else 
	             { incFreq (&Heap,id);
 		       rec = &Rec.records[id];
	               L[ant].next = rec->cpos;
	               L[L[ant].next].prev = ant;
	             }
	          L[ant].prev = -id-1;
	          rec->cpos = ant;
		}
	     C[cpos] = n;
	     if (ssgte != u) C[ssgte-1] = -cpos-1;
	     C[cpos+1] = -ssgte-1;
	     c--;
 	     orec = &Rec.records[oid]; // just in case of Rec.records realloc'd
	     cpos = orec->cpos;
	   }
	   
	if (PRNC) prnC();
	 removeRecord (&Rec,oid);
	 n++;
	 purgeHeap(&Heap); // remove freq 1 from heap
	 if (c < factor * u) // compact C
	    { int i,ni;
	      i = 0;
	      for (ni=0;ni<c-1;ni++) 
		{ C[ni] = C[i];
		  L[ni] = L[i];
		  if (L[ni].prev < 0) 
		     { if (L[ni].prev != NullFreq) // real ptr
			  Rec.records[-L[ni].prev-1].cpos = ni; 
		     }
		  else L[L[ni].prev].next = ni;
		  if (L[ni].next != -1) L[L[ni].next].prev = ni;
		  i++; if (C[i] < 0) i = -C[i]-1;
		}
	      C[ni] = C[i];
	      u = c;
	      C = realloc (C, c * sizeof(int));
	      L = realloc (L, c * sizeof(Tlist));
              assocRecords (&Rec,&Hash,&Heap,L);
	    }
       
       
    //*fari*/  
    i++;  //fari... para mostrar numero de iteracion 
    if ( ( i<10) || (! ((i-1)%100)) ) 
    	printf("Repair.compress: It: %d compressed: %3.15f %% |c| = %d , diff prev iter = %2.15f\n", i, 100.0*c/INI_c, c, (prev_ratio - (100.0*c/INI_c)) );
     //cout << "Repair.compress: It: " << i++ << " compressed: " << 100.*c/INI_c << "%" << " |c|=" << c << endl;
	//if ((100.*m/n)<43.0) break;
	//if ((100.0*c/INI_c)< CORTE_REPAIR) break;

	//if  (  ((prev_ratio - (100.0*c/INI_c)) < 0.00000009 )  ||  ((100.0*c/INI_c)< CORTE_REPAIR) ) break;
	
	//if  (  ((prev_ratio - (100.0*c/INI_c)) < 0.000000005 )  ||  (((prev_ratio - (100.0*c/INI_c)) < CORTE_REPAIR) ) ) 
	if    (((prev_ratio - (100.0*c/INI_c)) < CORTE_REPAIR) ) 
	break;

	  	
	prev_ratio = (100.0*c/INI_c);
	  	
} //while 
printf("Repair.compress: It: %d compressed: %3.15f %% |c| = %d , diff prev iter = %2.15f \n", i, 100.0*c/INI_c, c, (prev_ratio - (100.0*c/INI_c)) );
//printf("Repair.compress: It: %d compressed: %3.8f %% |c| = %d \n", i, 100.0*c/INI_c, c);
     return 0;
   }
Ejemplo n.º 6
0
static void
find_closest_pairs(double *place, int n, int num_pairs,
		   PairStack * pairs_stack)
{
    /* Fill the stack 'pairs_stack' with 'num_pairs' closest pairs int the 1-D layout 'place' */
    int i;
    PairHeap heap;
    int *left = N_GNEW(n, int);
    int *right = N_GNEW(n, int);
    Pair pair = { 0, 0 }, new_pair;

    /* Order the nodes according to their place */
    int *ordering = N_GNEW(n, int);
    int *inv_ordering = N_GNEW(n, int);

    for (i = 0; i < n; i++) {
	ordering[i] = i;
    }
    quicksort_place(place, ordering, 0, n - 1);
    for (i = 0; i < n; i++) {
	inv_ordering[ordering[i]] = i;
    }

    /* Intialize heap with all consecutive pairs */
    initHeap(&heap, place, ordering, n);

    /* store the leftmost and rightmost neighbors of each node that were entered into heap */
    for (i = 1; i < n; i++) {
	left[ordering[i]] = ordering[i - 1];
    }
    for (i = 0; i < n - 1; i++) {
	right[ordering[i]] = ordering[i + 1];
    }

    /* extract the 'num_pairs' closest pairs */
    for (i = 0; i < num_pairs; i++) {
	int left_index;
	int right_index;
	int neighbor;

	if (!extractMax(&heap, &pair)) {
	    break;		/* not enough pairs */
	}
	push(pairs_stack, pair);
	/* insert to heap "descendant" pairs */
	left_index = inv_ordering[pair.left];
	right_index = inv_ordering[pair.right];
	if (left_index > 0) {
	    neighbor = ordering[left_index - 1];
	    if (inv_ordering[right[neighbor]] < right_index) {
		/* we have a new pair */
		new_pair.left = neighbor;
		new_pair.right = pair.right;
		new_pair.dist = place[pair.right] - place[neighbor];
		insert(&heap, new_pair);
		right[neighbor] = pair.right;
		left[pair.right] = neighbor;
	    }
	}
	if (right_index < n - 1) {
	    neighbor = ordering[right_index + 1];
	    if (inv_ordering[left[neighbor]] > left_index) {
		/* we have a new pair */
		new_pair.left = pair.left;
		new_pair.right = neighbor;
		new_pair.dist = place[neighbor] - place[pair.left];
		insert(&heap, new_pair);
		left[neighbor] = pair.left;
		right[pair.left] = neighbor;
	    }
	}
    }
    free(left);
    free(right);
    free(ordering);
    free(inv_ordering);
    freeHeap(&heap);
}
Ejemplo n.º 7
0
/*The algorithm uses an idea similar to the standard MST algorithm*/
void TopoCentLB :: calculateMST(PartGraph *partgraph,LBTopology *topo,int *proc_mapping,int max_comm_part) {

  int *inHeap;
  double *keys;
  int count = partgraph->n_nodes;
  int i=0,j=0;

  //Arrays needed for keeping information
  inHeap = new int[partgraph->n_nodes];
  keys = new double[partgraph->n_nodes];

  int *assigned_procs = new int[count];

  hopCount = new double*[count];
  for(i=0;i<count;i++){
    proc_mapping[i]=-1;
    assigned_procs[i]=0;
    hopCount[i] = new double[count];
    for(j=0;j<count;j++)
      hopCount[i][j] = 0;
  }

  //Call a topology routine to fill up hopCount
  topo->get_pairwise_hop_count(hopCount);
	
  int max_neighbors = topo->max_neighbors();
	
  HeapNode *heap = new HeapNode[partgraph->n_nodes];
  heapMapping = new int[partgraph->n_nodes];
	
  int heapSize = 0;

  for(i=0;i<partgraph->n_nodes;i++){
    heap[i].key = 0.00;
    heap[i].node = i;
    keys[i] = 0.00;
    inHeap[i] = 1;
    heapMapping[i]=i;
  }

  //Assign the max comm partition first
  heap[max_comm_part].key = 1.00;
	
  heapSize = partgraph->n_nodes;
  BuildHeap(heap,heapSize);

  int k=0,comm_cnt=0,m=0;
  int *commParts = new int[partgraph->n_nodes];
	
  //srand(count);

  while(heapSize > 0){

    /****Phase1: Extracting appropriate partition from heap****/

    HeapNode max = extractMax(heap,&heapSize);
    inHeap[max.node] = 0;

    for(i=0;i<partgraph->n_nodes;i++){
      commParts[i]=-1;
      PartGraph::Edge wt = partgraph->edges[max.node][i];
      if(wt == 0)
	continue;
      if(inHeap[i]){
#ifdef MAX_EDGE
	if(wt>keys[i])
	  keys[i]=wt;
#else
	keys[i] += wt;
#endif
        /*This part has been COMMENTED out for optimizing the code: we handle the updation using heapMapping*/
        /*array instead of searching for node in the heap everytime*/

	//Update in the heap too
	//First, find where this node is..in the heap
	/*for(j=0;j<heapSize;j++)
	  if(heap[j].node == i)
	  break;
	  if(j==heapSize)
	  CmiAbort("Some error in heap...\n");*/
	increaseKey(heap,heapMapping[i],wt);
      }
    }
		 
    /*Phase2: ASSIGNING partition to processor*/
		
    //Special case
    if(heapSize == partgraph->n_nodes-1){ //Assign max comm partition to 0th proc in the topology
      proc_mapping[max.node]=0;
      assigned_procs[0]=1;
      continue;
    }
		
    m=0;

    comm_cnt=0;

    double min_cost=-1;
    int min_cost_index=-1;
    double cost=0;
    int p=0;
    //int q=0;

    for(k=0;k<partgraph->n_nodes;k++){
      if(!inHeap[k] && partgraph->edges[k][max.node]){
	commParts[comm_cnt]=k;
	comm_cnt++;
      }
    }

    //Optimized the loop by commenting out the get_hop_count code and getting all the hop counts initially
    for(m=0;m<count;m++){
      if(!assigned_procs[m]){
	cost=0;
	for(p=0;p<comm_cnt;p++){
	  //if(!hopCount[proc_mapping[commParts[p]]][m])
	  //hopCount[proc_mapping[commParts[p]]][m]=topo->get_hop_count(proc_mapping[commParts[p]],m);
	  cost += hopCount[proc_mapping[commParts[p]]][m]*partgraph->edges[commParts[p]][max.node];
	}
	if(min_cost==-1 || cost<min_cost){
	  min_cost=cost;
	  min_cost_index=m;
	}
      }
    }

    proc_mapping[max.node]=min_cost_index;
    assigned_procs[min_cost_index]=1;
  }

  //clear up memory
  delete[] inHeap;
  delete[] keys;
  delete[] assigned_procs;
  delete[] heap;
  delete[] commParts;
}