Example #1
0
int wpl_text_chunks::text::output_json (
		wpl_text_state *state,
		const set<wpl_value*> &vars,
		wpl_text_chunk_it *it,
		wpl_value *final_result
) {
	const char id_string[] = "id=\"";
	const int id_string_len = sizeof(id_string)-1;

	wpl_io &io = state->get_io();
	wpl_io_void io_void;
	wpl_value_string json_name;
	wpl_value_string json_value;
	wpl_value_unsafe_pointer unsafe_pointer;

	json_name.set_do_finalize();
	json_value.set_do_finalize();
	unsafe_pointer.set_do_finalize();

	/*
	   If we end with an HTML id tag, use this the text value of the
	   next chunk as the JSON name.
	   */
	if (strncmp (end - id_string_len, id_string, id_string_len) != 0) {
		return (*(++(*it)))->output_json(state, vars, it, final_result);
	}

	/*
	   If no return from the next block, just proceed with output_json
	   */
	if (!((*(++(*it)))->run(state, it->get_pos(), &json_name, io_void) & WPL_OP_OK)) {
		return (*it)->output_json(state, vars, it, final_result);
	}

	/*
	   The next block which returns WPL_OP_OK is the expression
	   whos pointer is used to match against the list of requested
	   variables to output.

	 */
	while (true) {
	   	// it++ throws wpl_text_chunk_end_reached() when we're done
		(*it)++;

		/*
		   Check if the next chuck is an expression with return value
		   */
		if (!((*it)->run(state, it->get_pos(), &unsafe_pointer, io_void) & WPL_OP_OK)) {
			continue;
		}

		/*
		   Check if the value exists in the list
		   */
		if (vars.find(unsafe_pointer.dereference()) == vars.end()) {
			continue;
		}

		/*
		   All OK, output this variable
		   */
		(*it)->run(state, it->get_pos(), &json_value, io_void);
		io << "\"";
		json_name.output_json(io);
		io << "\": \"";
		json_value.output_json(io);
		io << "\",\n";

		(*it)++;

		return (*it)->output_json(state, vars, it, final_result);
	}

	return WPL_OP_NO_RETURN;
}
Example #2
0
void BilinearFormUtility::computeOptimalStiffnessMatrix(FieldContainer<double> &stiffness, 
                                                        FieldContainer<double> &optimalTestWeights,
                                                        BilinearFormPtr bilinearForm,
                                                        Teuchos::RCP<DofOrdering> trialOrdering, Teuchos::RCP<DofOrdering> testOrdering,
                                                        shards::CellTopology &cellTopo, FieldContainer<double> &physicalCellNodes,
                                                        FieldContainer<double> &cellSideParities) {
  // lots of code copied and pasted from the very similar computeStiffnessMatrix.  The difference here is that for each optimal test function,
  // we need to ask the bilinear form about each of its components (it's a vector whereas the other guy had just a single basis function
  // for each...), and then apply the appropriate weights....
  // physicalCellNodes: the nodal points for the element(s) with topology cellTopo
  //                 The dimensions are (numCells, numNodesPerElement, spaceDimension)
  // optimalTestWeights dimensions are: (numCells, numTrial, numTest) -- numTrial is the optTest index
  // stiffness dimensions are: (numCells, # trialOrdering Dofs, # trialOrdering Dofs)
  // (while (cell,trial,test) is more natural conceptually, I believe the above ordering makes
  //  more sense given the inversion that we must do to compute the optimal test functions...)
  
  // steps:
  // 0. Set up BasisCache
  // 3. For each (test, trial) combination:
  //   a. Apply the specified operators to the basis in the DofOrdering, at the cubature points
  //   b. Multiply the two bases together, weighted with Jacobian/Piola transform and cubature weights
  //   c. Pass the result to bilinearForm's applyBilinearFormData method
  //   d. Sum up (integrate) and place in stiffness matrix according to DofOrdering indices
  
  // 0. Set up Cubature
  
  unsigned numCells = physicalCellNodes.dimension(0);
  unsigned numNodesPerElem = physicalCellNodes.dimension(1);
  unsigned spaceDim = physicalCellNodes.dimension(2);
  
  // Check that cellTopo and physicalCellNodes agree
  TEUCHOS_TEST_FOR_EXCEPTION( ( numNodesPerElem != cellTopo.getNodeCount() ),
                     std::invalid_argument,
                     "Second dimension of physicalCellNodes and cellTopo.getNodeCount() do not match.");
  TEUCHOS_TEST_FOR_EXCEPTION( ( spaceDim != cellTopo.getDimension() ),
                     std::invalid_argument,
                     "Third dimension of physicalCellNodes and cellTopo.getDimension() do not match.");
  
  int numOptTestFunctions = optimalTestWeights.dimension(1); // should also == numTrialDofs
  
  TEUCHOS_TEST_FOR_EXCEPTION( ( optimalTestWeights.dimension(1) != stiffness.dimension(2) ),
                     std::invalid_argument,
                     "optimalTestWeights.dimension(1) (=" << optimalTestWeights.dimension(1) << ") and stiffness.dimension(2) (=" << stiffness.dimension(2) << ") do not match.");
  TEUCHOS_TEST_FOR_EXCEPTION( ( stiffness.dimension(1) != stiffness.dimension(2) ),
                     std::invalid_argument,
                     "stiffness.dimension(1) (=" << stiffness.dimension(1) << ") and stiffness.dimension(2) (=" << stiffness.dimension(2) << ") do not match.");
  
  // Set up BasisCache
  int cubDegreeTrial = trialOrdering->maxBasisDegree();
  int cubDegreeTest = testOrdering->maxBasisDegree();
  int cubDegree = cubDegreeTrial + cubDegreeTest;
  
  BasisCache basisCache(physicalCellNodes, cellTopo, *trialOrdering, cubDegreeTest, true); // DO create side caches, too
  
  unsigned numSides = CamelliaCellTools::getSideCount(cellTopo);

  vector<int> testIDs = bilinearForm->testIDs();
  vector<int>::iterator testIterator;
  
  vector<int> trialIDs = bilinearForm->trialIDs();
  vector<int>::iterator trialIterator;
  
  BasisPtr trialBasis,testBasis;
  
  stiffness.initialize(0.0);
  
  for (trialIterator = trialIDs.begin(); trialIterator != trialIDs.end(); trialIterator++) {
    int trialID = *trialIterator;
    
    for (int optTestIndex=0; optTestIndex < numOptTestFunctions; optTestIndex++) {
      FieldContainer<double> weights(numCells,testOrdering->totalDofs());
      for (unsigned i=0; i<numCells; i++) {
        for (int j=0; j<testOrdering->totalDofs(); j++) {
          weights(i,j) = optimalTestWeights(i,optTestIndex,j);
        }
      }
      for (testIterator = testIDs.begin(); testIterator != testIDs.end(); testIterator++) {
        int testID = *testIterator;
        
        vector<EOperatorExtended> trialOperators, testOperators;
        bilinearForm->trialTestOperators(trialID, testID, trialOperators, testOperators);
        vector<EOperatorExtended>::iterator trialOpIt, testOpIt;
        testOpIt = testOperators.begin();
        
        int operatorIndex = -1;
        for (trialOpIt = trialOperators.begin(); trialOpIt != trialOperators.end(); trialOpIt++) {
          IntrepidExtendedTypes::EOperatorExtended trialOperator = *trialOpIt;
          IntrepidExtendedTypes::EOperatorExtended testOperator = *testOpIt;
          operatorIndex++;
          
          if (testOperator==OP_TIMES_NORMAL) {
            TEUCHOS_TEST_FOR_EXCEPTION(true,std::invalid_argument,"OP_TIMES_NORMAL not supported for tests.  Use for trial only");
          }
          
          Teuchos::RCP < const FieldContainer<double> > testValuesTransformed;
          Teuchos::RCP < const FieldContainer<double> > trialValuesTransformed;
          Teuchos::RCP < const FieldContainer<double> > testValuesTransformedWeighted;

          if (! bilinearForm->isFluxOrTrace(trialID)) {
            trialBasis = trialOrdering->getBasis(trialID);
            testBasis = testOrdering->getBasis(testID);
            FieldContainer<double> miniStiffness( numCells, testBasis->getCardinality(), trialBasis->getCardinality() );
            
            trialValuesTransformed = basisCache.getTransformedValues(trialBasis,trialOperator);
            testValuesTransformedWeighted = basisCache.getTransformedWeightedValues(testBasis,testOperator);
            
            FieldContainer<double> physicalCubaturePoints = basisCache.getPhysicalCubaturePoints();
            FieldContainer<double> materialDataAppliedToTrialValues = *trialValuesTransformed; // copy first
            FieldContainer<double> materialDataAppliedToTestValues = *testValuesTransformedWeighted; // copy first
            bilinearForm->applyBilinearFormData(materialDataAppliedToTrialValues,materialDataAppliedToTestValues, 
                                               trialID,testID,operatorIndex,physicalCubaturePoints);
              
            int testDofOffset = testOrdering->getDofIndex(testID,0);
            // note that weightCellBasisValues does depend on contiguous test basis dofs...
            // (this is the plan, since there shouldn't be any kind of identification between different test dofs,
            //  especially since test functions live only inside the cell)
            weightCellBasisValues(materialDataAppliedToTestValues, weights, testDofOffset);
              
            FunctionSpaceTools::integrate<double>(miniStiffness,materialDataAppliedToTestValues,materialDataAppliedToTrialValues,COMP_BLAS);
            // place in the appropriate spot in the element-stiffness matrix
            // copy goes from (cell,trial_basis_dof,test_basis_dof) to (cell,element_trial_dof,element_test_dof)
            
            // there may be a more efficient way to do this copying:
            // (one strategy would be to reimplement fst::integrate to support offsets, so that no copying needs to be done...)
            for (int i=0; i < testBasis->getCardinality(); i++) {
              for (int j=0; j < trialBasis->getCardinality(); j++) {
                int trialDofIndex = trialOrdering->getDofIndex(trialID,j);
                for (unsigned k=0; k < numCells; k++) {
                  stiffness(k,optTestIndex,trialDofIndex) += miniStiffness(k,i,j);
                }
              }
            }          
          } else {  // boundary integral
            int trialBasisRank = trialOrdering->getBasisRank(trialID);
            int testBasisRank = testOrdering->getBasisRank(testID);
            
            TEUCHOS_TEST_FOR_EXCEPTION( ( trialBasisRank != 0 ),
                               std::invalid_argument,
                               "Boundary trial variable (flux or trace) given with non-scalar basis.  Unsupported.");
            
            bool isFlux = false; // i.e. the normal is "folded into" the variable definition, so that we must take parity into account
            const set<int> normalOperators = BilinearForm::normalOperators();
            if (   (normalOperators.find(testOperator)  == normalOperators.end() ) 
                && (normalOperators.find(trialOperator) == normalOperators.end() ) ) {
              // normal not yet taken into account -- so it must be "hidden" in the trial variable
              isFlux = true;
            }
            
            for (unsigned sideOrdinal=0; sideOrdinal<numSides; sideOrdinal++) {
              trialBasis = trialOrdering->getBasis(trialID,sideOrdinal);
              testBasis = testOrdering->getBasis(testID);
              
              FieldContainer<double> miniStiffness( numCells, testBasis->getCardinality(), trialBasis->getCardinality() );
              
              // for trial: we never dot with normal, and the value lives on the side, so we don't use the volume coords either:
              trialValuesTransformed = basisCache.getTransformedValues(trialBasis,trialOperator,sideOrdinal,false);
              // for test: first, don't dot with normal, but do use the volume coords:
              //testValuesTransformed = basisCache.getTransformedValues(testBasis,testOperator,sideOrdinal,true);
              testValuesTransformedWeighted = basisCache.getTransformedWeightedValues(testBasis,testOperator,sideOrdinal,true);
              
              // copy before manipulating trialValues--these are the ones stored in the cache, so we're not allowed to change them!!
              FieldContainer<double> materialDataAppliedToTrialValues = *trialValuesTransformed;
              if (isFlux) {
                // this being a flux ==> take cell parity into account (because then there must be a normal folded into the flux definition)
                // we need to multiply the trialValues by the parity of the normal, since
                // the trial implicitly contains an outward normal, and we need to adjust for the fact
                // that the neighboring cells have opposite normal
                // trialValues should have dimensions (numCells,numFields,numCubPointsSide)
                int numFields = trialValuesTransformed->dimension(1);
                int numPoints = trialValuesTransformed->dimension(2);
                for (unsigned cellIndex=0; cellIndex<numCells; cellIndex++) {
                  double parity = cellSideParities(cellIndex,sideOrdinal);
                  if (parity != 1.0) {  // otherwise, we can just leave things be...
                    for (int fieldIndex=0; fieldIndex<numFields; fieldIndex++) {
                      for (int ptIndex=0; ptIndex<numPoints; ptIndex++) {
                        materialDataAppliedToTrialValues(cellIndex,fieldIndex,ptIndex) *= parity;
                      }
                    }
                  }
                }
              }
              
              FieldContainer<double> cubPointsSidePhysical = basisCache.getPhysicalCubaturePointsForSide(sideOrdinal);
              FieldContainer<double> materialDataAppliedToTestValues = *testValuesTransformedWeighted; // copy first
              bilinearForm->applyBilinearFormData(materialDataAppliedToTrialValues,materialDataAppliedToTestValues,
                                                 trialID,testID,operatorIndex,cubPointsSidePhysical);              
              
              int testDofOffset = testOrdering->getDofIndex(testID,0,0);
              weightCellBasisValues(materialDataAppliedToTestValues, weights, testDofOffset);
              
              //   d. Sum up (integrate) and place in stiffness matrix according to DofOrdering indices
              FunctionSpaceTools::integrate<double>(miniStiffness,materialDataAppliedToTestValues,materialDataAppliedToTrialValues,COMP_BLAS);
              // place in the appropriate spot in the element-stiffness matrix
              // copy goes from (cell,trial_basis_dof,test_basis_dof) to (cell,element_trial_dof,element_test_dof)
                            
              for (int i=0; i < testBasis->getCardinality(); i++) {
                for (int j=0; j < trialBasis->getCardinality(); j++) {
                  int trialDofIndex = trialOrdering->getDofIndex(trialID,j,sideOrdinal);
                  for (unsigned k=0; k < numCells; k++) {
                    stiffness(k,optTestIndex,trialDofIndex) += miniStiffness(k,i,j);
                  }
                }
              }
            }
          }
          testOpIt++;
        }
      }
    }
  }
}
Example #3
0
int _tmain(int argc, _TCHAR* argv[])
{
	long pmax = 10000000;
	vector<long> primes = sieve_of_eratosthenes(pmax);

	long long sum = 0;

	for (vector<long>::iterator it=primes.begin(); it!= primes.end(); it++)
	{
		long p = *it;

		// every 1 digit prime is a relative
		if (p<10) {
			relatives.insert(*it);
			continue;
		}

		bool condition_met = false;

		// condition 1
		// change all digits possible
		int len = findn(*it);
		for (long exponent=1; exponent < p ; exponent *= 10) {
			long limit = p/exponent % 10;
			long newp = p;
			for (int n=0; n<limit; n++) {
				newp -= exponent;
				if (relatives.find(newp) != relatives.end() && findn(newp) + 1 >= len) {
					relatives.insert(*it);
					exponent=p;
					n=limit;
					condition_met=true;
				}
			}
		}

		// condition 2
		// remove leftmost digit
		if ( condition_met == false ) {
			long newp = p % getexp(p);
			if (relatives.find(newp) != relatives.end() && findn(newp) + 1 >= len) {
				relatives.insert(*it);
				condition_met=true;
			}
		}

		if (condition_met) {
			if ( no_relatives.size() > 0 ) {
				set<long> erased = recheck_non_relatives(p);
				set<long> erased2;
				set<long> new_erased;

				while (erased.size() > 0) {
					erased2.clear();
					new_erased.clear();
					for (set<long>::iterator sit=erased.begin(); sit != erased.end(); sit++) {
						erased2 = recheck_non_relatives(*sit);
						for (set<long>::iterator sit2=erased2.begin(); sit2 != erased2.end(); sit2++) {
							new_erased.insert(*sit2);
						}
					}
					erased = new_erased;
				}
			}
		}
		else {
			no_relatives.insert(*it);
			sum += *it;
			cout << *it << endl;
		}
	}

	
	cout << "--------------" << endl << sum << endl;

	system("PAUSE");
	return 0;
}
bool contains(set<T> container, string key) {
	return container.find(key) != container.end();
}
Example #5
0
 virtual void handle() {
     // the host has departed
     //
     set<HOST*>::iterator i = hosts.find(this);
     hosts.erase(i);
 }
Example #6
0
		void addUrlIfNotContain(string url) {
			boost::mutex::scoped_lock mylock(urlsMutex);
			if ((parsedPages.find(url) == parsedPages.end()) && (pagesToParse.find(url) == pagesToParse.end())) {
				pagesToParse.insert(url);
			}
		}
Example #7
0
/*! Return true if a SPICE kernel has already been loaded, false if not.
 */
bool IsSpiceKernelLoaded(const string& filepath)
{
	return ResidentSpiceKernels.find(filepath) != ResidentSpiceKernels.end();
}
void dfs(string str, int deep)
{
	if (flag)
		return;
	if (str.size() == 47)
	{
		if (str == original)
		{
			flag = 1;
			times = deep;
		}
		return;
	}
	int i, j;
	for (i = 0; i < str.size(); ++i)
	{
		if (str[i] == 'C' || str[i] == 'O' || str[i] == 'W')
			break;
	}
	if (!prefix(str, i))
		return;
	if (str[i] != 'C')
		return;
	int pre = i + 1, start = i;
	bool cut = 0;
	for (i = pre; i < str.size(); ++i)
	{
		if (str[i] == 'C' || str[i] == 'O' || str[i] == 'W')
		{
			if (!sub(str, pre, i))
			{
				cut = 1;
				break;
			}
			pre = i + 1;
		}
	}
	if (cut)
		return;
	if (str[pre - 1] != 'W')
		return;
	if (!suffix(str, pre))
		return;
	for (j = 0; j < str.size(); ++j)
	{
		if (flag)
			return;
		for (i = 0; i < j; ++i)
		{
			if (flag)
				return;
			for (int k = str.size() - 1; k > j; --k)
			{
				if (flag)
					return;
				if (str[i] == 'C' && str[j] == 'O' && str[k] == 'W')
				{
					string temp;
					for (int l = 0; l < i; ++l)
						temp += str[l];
					for (int l = j + 1; l < k; ++l)
						temp += str[l];
					for (int l = i + 1; l < j; ++l)
						temp += str[l];
					for (int l = k + 1; l < str.size(); ++l)
						temp += str[l];
					if (st.find(temp) == st.end() && st.size() < 50000)   //Ì«¼ÙÁË- -
					{
						st.insert(temp);
						dfs(temp, deep + 1);
					}
				}
			}
		}
	}
}
Example #9
0
void add_include_names( const string& file_name, bool is_root_file = true )
{
   string path;

   ifstream inpf( file_name.c_str( ) );

   if( is_root_file && !inpf )
   {
      cerr << "Error: Unable to open source file '" << file_name << "' for input." << endl;
      exit( 1 );
   }

   if( !is_root_file )
   {
      set< string >::iterator i;
      for( i = include_paths.begin( ); i != include_paths.end( ); ++i )
      {
         string str( *i );
         str += '\\';
         str += file_name;

         inpf.clear( );
         inpf.open( str.c_str( ), ios::in );
         if( inpf )
         {
            path = *i;
            break;
         }
      }

      if( !inpf )
      {
         cerr << "Error: Unable to open source file '" << file_name << "' for input." << endl;
         exit( 1 );
      }

      string str( path );
      if( !str.empty( ) )
         str += '\\';

      str += file_name;
      transform_path_separators( str );

      if( include_names.find( str ) != include_names.end( ) )
         return;

      include_names.insert( str );
      size_t pos = str.find_last_of( '\\' );
      if( pos != string::npos )
      {
         string current = str.substr( 0, pos );
         if( include_paths.find( current ) == include_paths.end( ) )
            include_paths.insert( current );
      }
   }

   string line, include;
   while( getline( inpf, line ) )
   {
      if( get_include_name( line, include ) )
         add_include_names( include, false );
   }
}
Example #10
0
int main( ) {

    freopen( "ttwo.in", "r", stdin );
    freopen( "ttwo.out", "w", stdout );

    for ( int i = 1; i < MAXN; ++i ) {
        for ( int j = 1; j < MAXN; ++j ) {
            scanf( " %c", &maze[i][j] );
        }
    }
    
    for ( int i = 0; i <= MAXN; ++i ) {
        maze[0][i] = '*';
        maze[MAXN][i] = '*';
        maze[i][0] = '*';
        maze[i][MAXN] = '*';
    }

    state start;
    
    for ( int i = 1; i <= MAXN; ++i )
        for ( int j = 1; j <= MAXN; ++j ) {
            if ( maze[i][j] == 'F' ) {
                start.john_x = i;
                start.john_y = j;
                start.john_dir = NORTH;
                maze[i][j] = '.';
            }else if ( maze[i][j] == 'C' ) {
                start.cow_x = i;
                start.cow_y = j;
                start.cow_dir = NORTH;
                maze[i][j] = '.';
            }
        }
        
    start.cost = 0;
    
    q.push( start );
    s.insert( vstate( start ) );
    
    if ( check( start ) ) {
        printf( "0\n" );
        return 0;
    }
    
    while ( !q.empty() ) {
        
        state top = q.front();
        q.pop();
        
        ++top.cost;
       
        state tmp = top;
       
        if ( valid( top.cow_x + dx[ top.cow_dir ], top.cow_y + dy[ top.cow_dir ] ) ) {
                
            if ( maze[ top.cow_x + dx[ top.cow_dir ] ][ top.cow_y + dy[ top.cow_dir ] ] == '*' ) {
                tmp.cow_dir += 1;
                tmp.cow_dir %= MODN;
            }else {
                tmp.cow_x += dx[ tmp.cow_dir ];
                tmp.cow_y += dy[ tmp.cow_dir ];
            }
                
        }else {
            tmp.cow_dir += 1;
            tmp.cow_dir %= MODN;
        }
        
        if ( valid( top.john_x + dx[ top.john_dir ], top.john_y + dy[ top.john_dir ] ) ) {
            
            if ( maze[ top.john_x + dx[ top.john_dir ] ][ top.john_y + dy[ top.john_dir ] ] == '*' ) {
                tmp.john_dir += 1;
                tmp.john_dir %= MODN;
            }else {
                tmp.john_x += dx[ tmp.john_dir ];
                tmp.john_y += dy[ tmp.john_dir ];
            }

        }else {
            tmp.john_dir += 1;
            tmp.john_dir %= MODN;
        }
        
        if ( s.find( vstate( tmp ) ) == s.end( ) ) {
        
            q.push( tmp );
            s.insert( vstate( tmp ) );
            
            if ( check( tmp ) ) {
                printf( "%d\n", tmp.cost );
                found = true;
                break;
            }
            
        }
        
    }
    
    if ( !found ) {
        printf( "0\n" );
    }
    
    return 0;

}
Example #11
0
// Map the input segments down until reaching the target genome. If the
// target genome is above the source genome, fail miserably.
// Destructive to any data in the input or results list.
static hal_size_t mapRecursiveDown(list<MappedSegmentPtr> &input, list<MappedSegmentPtr> &results, const Genome *tgtGenome,
                                   const set<string> &namesOnPath, bool doDupes, hal_size_t minLength) {
    list<MappedSegmentPtr> *inputPtr = &input;
    list<MappedSegmentPtr> *outputPtr = &results;

    if (inputPtr->empty()) {
        results = *inputPtr;
        return 0;
    }

    const Genome *curGenome = (*inputPtr->begin())->getGenome();
    assert(curGenome != NULL);
    if (curGenome == tgtGenome) {
        results = *inputPtr;
        return 0;
    }

    // Find the correct child to move down into.
    const Genome *nextGenome = NULL;
    hal_size_t nextChildIndex = numeric_limits<hal_size_t>::max();
    const Alignment *alignment = curGenome->getAlignment();
    vector<string> childNames = alignment->getChildNames(curGenome->getName());
    for (hal_size_t child = 0; nextGenome == NULL && child < childNames.size(); ++child) {
        if (childNames[child] == tgtGenome->getName() || namesOnPath.find(childNames[child]) != namesOnPath.end()) {
            const Genome *childGenome = curGenome->getChild(child);
            nextGenome = childGenome;
            nextChildIndex = child;
        }
    }

    if (nextGenome == NULL) {
        throw hal_exception("Could not find correct child that leads from " + curGenome->getName() + " to " +
                            tgtGenome->getName());
    }

    assert(nextGenome->getParent() == curGenome);

    // Map the actual segments down.
    list<MappedSegmentPtr>::iterator i = inputPtr->begin();
    for (; i != inputPtr->end(); ++i) {
        assert((*i)->getGenome() == curGenome);
        mapDown(*i, nextChildIndex, *outputPtr, minLength);
    }

    // Find paralogs.
    if (doDupes == true) {
        swap(inputPtr, outputPtr);
        outputPtr->clear();
        list<MappedSegmentPtr>::iterator i = inputPtr->begin();
        for (; i != inputPtr->end(); ++i) {
            assert((*i)->getGenome() == nextGenome);
            mapSelf(*i, *outputPtr, minLength);
        }
    }

    if (nextGenome != tgtGenome) {
        // Continue the recursion.
        swap(inputPtr, outputPtr);
        outputPtr->clear();
        mapRecursiveDown(*inputPtr, *outputPtr, tgtGenome, namesOnPath, doDupes, minLength);
    }

    if (outputPtr != &results) {
        results = *outputPtr;
    }

    results.sort(MappedSegment::LessSourcePtr());
    results.unique(MappedSegment::EqualToPtr());
    return results.size();
}
	long long getSum(int n, int q, int A, int B, int C){
		ll a = A, b = B, c = C;
		::n = n;
		have.clear();
		for(int i = 0; i < n; i++) {
			a = (a * b + c) % mod;
			ll p = a % (mod - n + i + 1);
			if(have.find(p) != have.end())
				p = mod - n + i;
			have.insert(p);
			arr[i] = mpr(p, i);
		}
		for(int i = 0; i < q; i++) {
			a = (a * b + c) % mod;
			que[i].first = a % n;
			a = (a * b + c) % mod;
			que[i].second = a;
		}
		sort(arr, arr + n);
		nl = 0, nr = 0;
		for(int i = 0; i < n; i++) {
			if(arr[i].first % 2 == 0)
				r[nr++] = arr[i];
			else
				l[nl++] = arr[i];
			loc[arr[i].second] = i;
		}

		ll ans = 0;
		for(int i = 0; i < q; i++) {
			int rloc = loc[que[i].first];
			int pl = 0, pr = nl - 1;
			while(pl != pr) {
				int mid = (pl + pr) / 2;
				int rl = 0, rr = nr;
				while(rl < rr) {
					int rmid = (rl + rr) / 2;
					if(l[mid].first - que[i].second * 2 > r[rmid].first)
						rl = rmid + 1;
					else rr = rmid;
				}
				if(mid + rl >= rloc)
					pr = mid;
				else pl = mid + 1;
			}
			int pans = pl;
			int rl = 0, rr = nr;
			while(rl < rr) {
				int rmid = (rl + rr) / 2;
				if(l[pl].first - que[i].second * 2 > r[rmid].first)
					rl = rmid + 1;
				else rr = rmid;
			}
			pans += rl;
			if(pans == rloc) {
				ans += abs(l[pl].first - que[i].second);
				continue;
			}
			pl = 0, pr = nr - 1;
			while(pl != pr) {
				int mid = (pl + pr) / 2;
				int rl = 0, rr = nl;
				while(rl < rr) {
					int rmid = (rl + rr) / 2;
					if(r[mid].first + que[i].second * 2 > l[rmid].first)
						rl = rmid + 1;
					else rr = rmid;
				}
				pans = mid + rl;
				if(mid + rl >= rloc)
					pr = mid;
				else pl = mid + 1;
			}
			ans += abs(r[pl].first + que[i].second);
			//
			#ifdef DEBUG //......................................................................................................
			pans = pl;
			rl = 0, rr = nl;
			while(rl < rr) {
				int rmid = (rl + rr) / 2;
				if(r[pl].first + que[i].second * 2 > l[rmid].first)
					rl = rmid + 1;
				else rr = rmid;
			}
			pans += rl;
			if(pans != rloc) {
				cerr << 1 << endl;
			}
			#endif //...........................................................................................................

		}

		return ans;
	}
Example #13
0
bool IpDoesPush (ADDRINT ip)
{
  return (pushIps.find(ip) != pushIps.end());
}
Example #14
0
void CSSHScheduler::scheduleTasks(const CTopoCore& _topology,
                                  const weakChannelInfoVector_t& _channels,
                                  hostToChannelMap_t& _hostToChannelMap,
                                  set<uint64_t>& _scheduledTasks,
                                  const set<uint64_t>& _tasksInCollections,
                                  bool useRequirement,
                                  const CTopoCore::IdSet_t* _addedTasks)
{
    STopoRuntimeTask::FilterIteratorPair_t tasks = _topology.getRuntimeTaskIterator();
    for (auto it = tasks.first; it != tasks.second; it++)
    {
        uint64_t id = it->first;

        // Check if tasks is in the added tasks
        if (_addedTasks != nullptr && _addedTasks->find(it->first) == _addedTasks->end())
            continue;

        // Check if task has to be scheduled in the collection
        if (_tasksInCollections.find(id) != _tasksInCollections.end())
            continue;

        // Check if task was already scheduled in the collection
        if (_scheduledTasks.find(id) != _scheduledTasks.end())
            continue;

        CTopoTask::Ptr_t task = it->second.m_task;

        // First path only for tasks with requirements;
        // Second path for tasks without requirements.

        // SSH scheduler doesn't support multiple requirements
        if (task->getNofRequirements() > 1)
        {
            stringstream ss;
            ss << "Unable to schedule task <" << id << "> with path " << task->getPath()
               << ": SSH scheduler doesn't support multiple requirements.";
            throw runtime_error(ss.str());
        }

        CTopoRequirement::Ptr_t requirement = (task->getNofRequirements() == 1) ? task->getRequirements()[0] : nullptr;
        if ((useRequirement && requirement == nullptr) || (!useRequirement && requirement != nullptr))
            continue;

        bool taskAssigned = false;

        for (auto& v : _hostToChannelMap)
        {
            const bool requirementOk = checkRequirement(requirement, useRequirement, v.first.first, v.first.second);
            if (requirementOk)
            {
                if (!v.second.empty())
                {
                    size_t channelIndex = v.second.back();
                    const auto& channel = _channels[channelIndex];

                    SSchedule schedule;
                    schedule.m_weakChannelInfo = channel;
                    schedule.m_taskInfo = it->second;
                    schedule.m_taskID = id;
                    m_schedule.push_back(schedule);

                    v.second.pop_back();

                    taskAssigned = true;

                    break;
                }
            }
        }
        if (!taskAssigned)
        {
            LOG(debug) << toString();
            stringstream ss;
            string requirementStr = (useRequirement)
                                        ? ("Requirement " + requirement->getName() + " couldn't be satisfied.")
                                        : "Not enough worker nodes.";
            ss << "Unable to schedule task <" << id << "> with path " << task->getPath() << ".\n" << requirementStr;
            throw runtime_error(ss.str());
        }
    }
}
Example #15
0
/*
 * ===  FUNCTION  ======================================================================
 *         Name:  removeDeadEndNodes
 *  Description:  remove dead end nodes and their incident edges
 * =====================================================================================
 */
UINT64 OverlapGraphSimple::removeParDeadEndNodes(map<UINT64, t_edge_vec* > *parGraph, set<UINT64> &markedNodes, vector<UINT64> &nodeList)
{
	CLOCKSTART;
	vector<UINT64> nodes_to_remove;
	#pragma omp parallel for schedule(dynamic) num_threads(p_ThreadPoolSize)
	for(size_t i=0; i<nodeList.size(); i++)
	{
		map<UINT64, vector<EdgeSimple*> * >::iterator it=parGraph->find(nodeList[i]);
		if(!it->second->empty())	// If the read has some edges.
		{
			bool isDeadEnd = true;	// flag for dead end edge
			UINT64 inEdge = 0; 	// number of incoming edges to this node
			UINT64 outEdge = 0; 	// number of outgoing edges from this node

			// Find number of in- and out- edges
			for(UINT64 j=0; j < it->second->size(); j++)
			{
				EdgeSimple * edge = it->second->at(j);

				//If edge points to a node not marked in this partition donot assume dead end delete it.
				UINT64 destID = edge->getDestinationRead();
				if(markedNodes.find(destID) == markedNodes.end())
				{
					isDeadEnd = false;
					break;
				}
				/* Break case:
				 * 0. edge already marked as not dead end
				 * 1. composite edge with more than minReadsCountInEdgeToBeNotDeadEnd (deafult: 10)
				 * 2. composite edge longer than minEdgeLengthToBeNotDeadEnd (default: 500)
				 * 3. the edge is loop for the current node
				 * Then flag=1 and exit the loop
				 */

				if (edge->isNotDeadEnd()){
					isDeadEnd = false;
					break;
				}
				if(edge->isListofReads() && edge->getListofReadsSize() >= minReadsCountInEdgeToBeNotDeadEnd) {
					edge->markNotDeadEnd();
					isDeadEnd = false;
					break;
				}
				if(edge->getEdgeLength() >= minEdgeLengthToBeNotDeadEnd) {
					edge->markNotDeadEnd();
					isDeadEnd = false;
					break;
				}
				if(edge->isLoop())
				{
					edge->markNotDeadEnd();
					isDeadEnd = false;
					break;
				}

				if((edge->getOrientation() >> 1) & 1)
					++outEdge;
				else
					++inEdge;
			}
			// no good edges incident to the node and only in-edges or out-edges
			if( isDeadEnd && inEdge*outEdge == 0 && inEdge + outEdge > 0){
				#pragma omp critical(updateNodeList)
				{
					nodes_to_remove.push_back(it->first);
				}
			}
		}
Example #16
0
void addLocations(const vector<MemoryBlock> &blocks,unsigned int value,const set<BlockValueLocation> &locationsToIntersect,vector<BlockValueLocation> &newLocations,const vector<pair<unsigned char *,int> > &ramBlocks)
{
	//cout << "ON SIZE: " << sizeof(T) << endl;
	for(int a=0;a<(int)blocks.size();a++)
	{
		//cout << "ON BLOCK: " << a << " WITH SIZE " << blocks[a].size << endl;
		for(int b=0;b<int(blocks[a].size);b++)
		{
			//cout << "BLOCK INDEX: " << b << endl;
			//if(b<=(int(blocks[a].size)-sizeof(T)))
      //cout << "IN RANGE\n";
			//cout << "VALUE: " << *((T*)(blocks[a].data+b)) << endl;
			if(b>(int(blocks[a].size)-sizeof(T))) continue;
			if( (((T)value) == *((T*)(blocks[a].data+b))) )
			{
				bool doNotAdd=false;
				if(!doNotAdd)
				{
					BlockValueLocation bvl(0,a,b,sizeof(T),0);
					if(locationsToIntersect.empty()==false)
					{
						doNotAdd=false;
						if(locationsToIntersect.find(bvl)==locationsToIntersect.end())
              doNotAdd=true;
						if(!doNotAdd)
						{
							newLocations.push_back(bvl);
						}
					}
					else
          {
						newLocations.push_back(bvl);
					}
				}
			}
    }
  }
	//cout << "ON SIZE: " << sizeof(T) << endl;
	for(int a=0;a<(int)ramBlocks.size();a++)
	{
		//cout << "ON BLOCK: " << a << " WITH SIZE " << blocks[a].size << endl;
		for(int b=0;b<int(ramBlocks[a].second);b++)
		{
			//cout << "BLOCK INDEX: " << b << endl;
			//if(b<=(int(blocks[a].size)-sizeof(T)))
      //cout << "IN RANGE\n";
			//cout << "VALUE: " << *((T*)(blocks[a].data+b)) << endl;
			if(b>(int(ramBlocks[a].second)-sizeof(T))) continue;
			if( (((T)value) == *((T*)(ramBlocks[a].first+b))) )
			{
				bool doNotAdd=false;
				if(!doNotAdd)
				{
					BlockValueLocation bvl(1,a,b,sizeof(T),0);
					if(locationsToIntersect.empty()==false)
					{
						doNotAdd=false;
						if(locationsToIntersect.find(bvl)==locationsToIntersect.end())
							doNotAdd=true;
						if(!doNotAdd)
						{
							newLocations.push_back(bvl);
						}
					}
					else
					{
						newLocations.push_back(bvl);
					}
				}
			}
		}
	}
}
// The execution function for the retransmission thread
void FMTPSender::RunRetransThread(int sock, map<uint, int>& retrans_fd_map, set<uint>& timeout_set) {
	int sock_fd = sock;

	map<uint, int>::iterator it;

	char recv_buf[FMTP_PACKET_LEN];
	FmtpHeader* recv_header = (FmtpHeader*)recv_buf;
	char* recv_packet_data = recv_buf + FMTP_HLEN;
	FmtpRetransRequest* retx_request = (FmtpRetransRequest*)recv_packet_data;

	char send_buf[FMTP_PACKET_LEN];
	FmtpHeader* send_header = (FmtpHeader*)send_buf;
	char* send_packet_data = send_buf + FMTP_HLEN;

	while (true) {
		if (retrans_tcp_server->Receive(sock_fd, recv_header, FMTP_HLEN) <= 0) {
			SysError("FMTPSender::RunRetransThread()::receive header error");
		}

		// Handle a retransmission request
		if (recv_header->flags & FMTP_RETRANS_REQ) {
			if (retrans_tcp_server->Receive(sock_fd, retx_request, recv_header->data_len) < 0) {
				SysError("FMTPSender::RunRetransThread()::receive retx request data error");
			}

			MessageMetadata* meta = metadata.GetMetadata(retx_request->msg_id);
			if (meta == NULL) {
				//cout << "Error: could not find metadata for file " << retx_request->msg_id << endl;
				continue;
			} else if (timeout_set.find(retx_request->msg_id) != timeout_set.end()) {
				continue;
			}

			// check whether the retransmission for the file has already time out
			if (GetElapsedSeconds(meta->multicast_start_cpu_time) > meta->retx_timeout_seconds) {
				//cout << "Retx timeout for file " << retx_request->msg_id << ".  Elapsed Time: "
				//		<< GetElapsedSeconds(meta->multicast_start_cpu_time) << "    Timeout: " << meta->retx_timeout_seconds << endl;
				send_header->session_id = retx_request->msg_id;
				send_header->flags = FMTP_RETRANS_TIMEOUT;
				send_header->data_len = 0;
				retrans_tcp_server->SelectSend(sock_fd, send_buf, FMTP_HLEN);

				timeout_set.insert(retx_request->msg_id);
			}
			else if (meta->is_disk_file) {	// is disk file transfer
				FileMessageMetadata* file_meta = (FileMessageMetadata*)meta;

				// get the file descriptor to read data from the file
				int fd;
				if ( (it = retrans_fd_map.find(recv_header->session_id)) != retrans_fd_map.end()) {
					fd = it->second;
				}
				else {
					if ( (fd = open(file_meta->file_name.c_str(), O_RDONLY)) < 0)
						SysError("FMTPSender::RunRetransThread() file open error");
					else
						retrans_fd_map[recv_header->session_id] = fd;
				}


				// send the missing blocks to the receiver
				lseek(fd, retx_request->seq_num, SEEK_SET);
				size_t remained_size = retx_request->data_len;
				size_t curr_pos = retx_request->seq_num;
				send_header->session_id = recv_header->session_id;
				send_header->flags = FMTP_RETRANS_DATA;
				while (remained_size > 0) {
					size_t data_length =
							remained_size > FMTP_DATA_LEN ? FMTP_DATA_LEN
									: remained_size;
					send_header->seq_number = curr_pos;
					send_header->data_len = data_length;

					read(fd, send_packet_data, send_header->data_len);
					retrans_tcp_server->SelectSend(sock_fd, send_buf, FMTP_HLEN + send_header->data_len);

					curr_pos += data_length;
					remained_size -= data_length;

					// Update statistics
					send_stats.total_retrans_packets++;
					send_stats.total_retrans_bytes += send_header->data_len;
					//file_meta->stats.session_retrans_packets++;
					//file_meta->stats.session_retrans_bytes += header->data_len;
				}
			}
			else {	// is memory data transfer

			}
		}
		else if (recv_header->flags & FMTP_RETRANS_END) {
			if (retrans_tcp_server->Receive(sock_fd, retx_request, recv_header->data_len) < 0) {
				SysError("FMTPSender::RunRetransThread()::receive retx end msg error");
			}

			// send back the retransmission end message to the receiver
			send_header->session_id = recv_header->session_id;
			send_header->seq_number = 0;
			send_header->data_len = 0;
			send_header->flags = FMTP_RETRANS_END;
			retrans_tcp_server->SelectSend(sock_fd, send_header, FMTP_HLEN);

			map<uint, int>::iterator it = retrans_fd_map.find(recv_header->session_id);
			if ( it != retrans_fd_map.end() ) {
				close(it->second);
				retrans_fd_map.erase(it);
			}

			if ( timeout_set.find(recv_header->session_id) != timeout_set.end() )
				timeout_set.erase(recv_header->session_id);

			// mark the completion of retransmission to one receiver
			metadata.RemoveFinishedReceiver(recv_header->session_id, sock_fd);
		}
		else if (recv_header->flags & FMTP_HISTORY_STATISTICS) {
			char* buf = new char[recv_header->data_len + 1];
			if (retrans_tcp_server->Receive(sock_fd, buf, recv_header->data_len) < 0) {
				break;
			}

			buf[recv_header->data_len] = '\0';
			status_proxy->SendMessageLocal(EXP_RESULT_REPORT, buf);
			delete[] buf;
			cout << "Received a history statistics from socket " << sock_fd << endl;
		}
	}

	cout << "Retransmission thread exited for socket " << sock_fd  << endl;
}
Example #18
0
int Canvas::_key_up(lua_State *l) {
	int key = pop_key(l);
	lua_pushboolean(l, keys_up.find(key) != keys_up.end());
	return 1;
}
Example #19
0
File: ff.cpp Project: yjwudi/oj
int main()
{
    int i = 0, j = 0, k = 0, idx;
    int a, b;
    P e;
    scanf("%d %d", &n, &m);
    for(i = 0; i < m; i++)
    {
        scanf("%d %d", &a, &b);
        G[a].push_back(b);
        G[b].push_back(a);
        ori_edges.push_back(make_pair(a, b));
    }
    Fill(parent, 0);
    Fill(dfn, 0);
    Fill(low, 0);
    Fill(vis, 0);
    get_bridge(1);
    /*for(it = bridge.begin(); it != bridge.end(); it++)
        cout << (*it).first << " " << (*it).second << endl;*/
    Fill(vis, 0);
    Fill(tag, 0);
    count_ = 0;
    ans = 0;
    for(i = 1; i <= n; i++)
    {
        if(!vis[i])
        {//Debug(i);
            cnt = 0;
            count_++;
            dfs_common(i);
            //Debug(cnt);
            //ans = max(ans, cnt);
            if(cnt > ans)
            {
                ans = cnt;
                idx = count_;
            }
        }
    }
    //4 0 1 1 0 0 1
    /*for(i = 1;  i<= n; i++)
        cout << tag[i] << " ";
    cout << endl;*/
    //Fill(tag_inv, 0);
    /*
    将bridge中的边转换为用tag值练成的边,存到G2中
    */
    for(it = bridge.begin(); it != bridge.end(); it++)
    {
        e = (*it);
        G2[tag[e.first]].push_back(e);
    }
    /*
    对G2的点进行深搜,按照顺序连边,并且把tag转为边的点
    */
    //Debug(idx);
    dfs_bridge(idx, -1);

    printf("%d\n", ans);
    for(i = 0; i < m; i++)
    {
        if(ans_set.find(ori_edges[i])!=ans_set.end())
        {
            printf("%d %d\n", ori_edges[i].second, ori_edges[i].first);
        }
        else
        {
            printf("%d %d\n", ori_edges[i].first, ori_edges[i].second);
        }
    }

    return 0;
}
	bool is_edge(int i, int j) const{ return _edges.find(make_tuple(i,j))!=_edges.end();}
Example #21
0
static int FillShapeValueJson (v8::Isolate* isolate,
                               VocShaper* shaper,
                               TRI_shape_value_t* dst,
                               v8::Handle<v8::Value> const json,
                               size_t level,
                               set<int>& seenHashes,
                               vector<v8::Handle<v8::Object>>& seenObjects,
                               bool create) {
  v8::HandleScope scope(isolate);

  if (json->IsRegExp() || json->IsFunction() || json->IsExternal()) {
    LOG_TRACE("shaper failed because regexp/function/external/date object cannot be converted");
    return TRI_ERROR_BAD_PARAMETER;
  }
  
  if (json->IsNull() || json->IsUndefined()) {
    return FillShapeValueNull(shaper, dst);
  }

  if (json->IsBoolean()) {
    return FillShapeValueBoolean(shaper, dst, json->ToBoolean());
  }

  if (json->IsBooleanObject()) {
    return FillShapeValueBoolean(shaper, dst, v8::Handle<v8::BooleanObject>::Cast(json));
  }

  if (json->IsNumber()) {
    return FillShapeValueNumber(shaper, dst, json->ToNumber());
  }

  if (json->IsNumberObject()) {
    return FillShapeValueNumber(shaper, dst, v8::Handle<v8::NumberObject>::Cast(json));
  }

  if (json->IsString()) {
    return FillShapeValueString(shaper, dst, json->ToString());
  }

  if (json->IsStringObject()) {
    return FillShapeValueString(shaper, dst, v8::Handle<v8::StringObject>::Cast(json)->ValueOf());
  }

  else if (json->IsArray()) {
    return FillShapeValueList(isolate, shaper, dst, v8::Handle<v8::Array>::Cast(json), level, seenHashes, seenObjects, create);
  }

  if (json->IsObject()) {
    v8::Handle<v8::Object> o = json->ToObject();
    v8::Handle<v8::String> toJsonString = TRI_V8_PAIR_STRING("toJSON", 6);
    if (o->Has(toJsonString)) {
      v8::Handle<v8::Value> func = o->Get(toJsonString);
      if (func->IsFunction()) {
        v8::Handle<v8::Function> toJson = v8::Handle<v8::Function>::Cast(func);

        v8::Handle<v8::Value> args;
        v8::Handle<v8::Value> result = toJson->Call(o, 0, &args);

        if (! result.IsEmpty()) {
          return FillShapeValueString(shaper, dst, result->ToString());
        }
      }
    }

    // fall-through intentional
  
    // check for cycles
    int hash = o->GetIdentityHash();

    if (seenHashes.find(hash) != seenHashes.end()) {
      for (auto it = seenObjects.begin();  it != seenObjects.end();  ++it) {
        if (json->StrictEquals(*it)) {
          return TRI_ERROR_ARANGO_SHAPER_FAILED;
        }
      }
    }
    else {
      seenHashes.insert(hash);
    }

    seenObjects.push_back(o);
    int res = FillShapeValueArray(isolate, shaper, dst, json->ToObject(), level, seenHashes, seenObjects, create);
    seenObjects.pop_back();
    // cannot remove hash value from seenHashes because multiple objects might have the same
    // hash values (collisions)
    return res;
  }

  LOG_TRACE("shaper failed to convert object");
  return TRI_ERROR_BAD_PARAMETER;
}
	//if is_arc(i,j) is true, is_arc(j,i ) is false
	//IMORTANT: is_no_edge() is false for (i,j) AND (j,i)
 	bool is_arc(int i, int j) const{ return _arcs.find(make_tuple(i,j))!=_arcs.end(); }
bool check(int c, int o, int cpo) {
    return city[c] && oper[o] && T.find(cpo) != T.end();
}
Example #24
0
void ProcessFile(
    const string& fileName,
    const char* programName,
    FILE* fp,
    const vector<string>& includePath,
    string& prependDir,
    size_t nesting,
    set<string, less<string> >& cache,
    PrintFunc printFunc,
    bool& warn)
{
    printFunc(fileName);

    if (nesting == 100)
    {
        ErrorExit(programName,
            "Infinite include file recursion? nesting level reached 100");
    }

    PEGASUS_ASSERT(fp != NULL);

    // For each line in the file:

    char line[4096];
    size_t lineNumber = 1;

    for (; fgets(line, sizeof(line), fp) != NULL; lineNumber++)
    {
        // Check for include directive:

        string path;
        char openDelim;

        if (line[0] == '#' &&
            GetIncludePath(fileName, lineNumber, line, path, openDelim))
        {
            // ATTN: danger! not distinguising between angle brack delimited
            // and quote delimited paths!

            set<string, less<string> >::const_iterator pos
                = cache.find(path);

            if (pos != cache.end())
            {
                continue;
            }

            cache.insert(path);

            string fullPath;
            FILE* includeFp =
                FindFile(includePath, prependDir, path, openDelim, fullPath);

            if (!includeFp)
            {
                if (warn)
                {
                    string message = "header file not found: " + path +
                        " included from " + fileName;
                    Warning(programName, message);
                }
            }
            else
            {
                ProcessFile(fullPath, programName, includeFp, includePath,
                    prependDir, nesting + 1, cache, printFunc, warn);
            }
        }
    }

    fclose(fp);
}
Example #25
0
bool isVisited(const set<Node>& visited,const Node& node)
{
	if(visited.find(node) == visited.end())
		return false;
	return true;
}
Example #26
0
int PalindromizationDiv1::getMinimumCost(string s, vector <string> op) {
    int n = op.size();
    for (int i = 0;i < n;i++)
    {
        if (op[i][0] == 'a')
        {
            sscanf(op[i].c_str(),"%s%s%d",tmp,o[i].c1,&o[i].cost);
            o[i].typ = 0;
        }
        else if (op[i][0] == 'e')
        {
            sscanf(op[i].c_str(),"%s%s%d",tmp,o[i].c1,&o[i].cost);
            o[i].typ = 1;
        }
        else if (op[i][0] == 'c')
        {
            sscanf(op[i].c_str(),"%s%s%s%d",tmp,o[i].c1,o[i].c2,&o[i].cost);
            o[i].typ = 2;
        }
    }
    node now;
    hash.clear();
    while (!Q.empty())  Q.pop();
    Q.push(node(s,0));
    hash.insert(s);
    int tim = 0;
    while (!Q.empty())
    {
        now = Q.top();
        Q.pop();
        if (palindrome(now.now) == true)    return now.cost;
        tmp1 = now.now;
        if (tmp1.size() > s.size()*2)   continue;
        for (int i = 0;i < n;i++)
        {
            if (o[i].typ == 0)
            {
                for (int j = 0;j <= tmp1.size();j++)
                {
                    tmp2 = tmp1.substr(0,j)+o[i].c1[0]+tmp1.substr(j,tmp1.size()-j);
                    if (hash.find(tmp2) == hash.end())
                    {
                        hash.insert(tmp2);
                        Q.push(node(tmp2,now.cost+o[i].cost));
                    }
                }
            }
            else if (o[i].typ == 1)
            {
                for (int j = 0;j < tmp1.size();j++)
                    if (tmp1[j] == o[i].c1[0])
                    {
                        tmp2 = tmp1.substr(0,j)+tmp1.substr(j+1,tmp1.size()-j-1);
                        if (hash.find(tmp2) == hash.end())
                        {
                            hash.insert(tmp2);
                            Q.push(node(tmp2,now.cost+o[i].cost));
                        }
                    }
            }
            else if (o[i].typ == 2)
            {
                for (int j = 0;j < tmp1.size();j++)
                    if (tmp1[j] == o[i].c1[0])
                    {
                        tmp2 = tmp1;
                        tmp2[j] = o[i].c2[0];
                        if (hash.find(tmp2) == hash.end())
                        {
                            hash.insert(tmp2);
                            Q.push(node(tmp2,now.cost+o[i].cost));
                        }
                    }
            }
        }
    }
    return -1;
}
Example #27
0
File: vd.cpp Project: cerdogan/Job
/* ******************************************************************************************** */
void vd () {

	// Process the site and circle events 
	while(!eventQueue.empty()) {

		// avl.draw();
		getchar2();

		// Check if it is a site event
		Event* event = eventQueue.top();
		eventQueue.pop();
		SiteEvent* siteEvent = dynamic_cast <SiteEvent*> (event);
		if(siteEvent != NULL) {

			printf("\n--- site --------------------------------------------------\n");
			
			// Update the sweep line location
			sweepLine = siteEvent->point(1) - 0.0001;
			printf("sweepLine: %lf\n", sweepLine);
			printf("new site: (%lf, %lf)\n", siteEvent->point(0), siteEvent->point(1));
			//avl.draw();
			getchar2();

			// Locate the existing arc information
			pair <bool, AVL<TreeNode*>::Node*> searchRes = 
				avl.search_candidateLoc(new TreeNode(siteEvent->pi, -1, true));

			// The tree is empty. Temporarily add the site information as a dummy node
			if(searchRes.second == NULL) {
				avl.insert(new TreeNode(siteEvent->pi, -1, true));
				printf("Tree empty!\n");
				continue;
			}

			// The tree still doesn't have a break point, but just a dummy site node information
			TreeNode* parentNode = searchRes.second->value;
			if(parentNode->dummy) {
				avl.remove(parentNode);
				avl.insert(new TreeNode(parentNode->p0i, siteEvent->pi));
				avl.insert(new TreeNode(siteEvent->pi, parentNode->p0i));
				printf("Tree dummy!\n");
				continue;
			}
			
			// Determine the site by comparing it with the found node value
			int prevSiteIdx = 0;
			if(parentNode->value() < siteEvent->point(0)) prevSiteIdx = parentNode->p1i;
			else prevSiteIdx = parentNode->p0i;
			printf("Previous site idx: (%d)\n", prevSiteIdx);
			
			// Create the new break points
			TreeNode* newNode1 = new TreeNode(siteEvent->pi, prevSiteIdx);
			TreeNode* newNode2 = new TreeNode(prevSiteIdx, siteEvent->pi);
 			avl.insert(newNode1);
 			avl.insert(newNode2);

			// Check for "false alarms" for circle events
			set <pair<CircleEvent*, Vector2d>, Vector2dComp>::iterator it =  allCircles.begin();
			printf("# parent circles: %d\n", parentNode->circleEvents.size());
//			for(size_t c_i = 0; c_i < parentNode->circleEvents.size(); c_i++) {
			for(; it != allCircles.end(); it++) {
//				CircleEvent* ce = parentNode->circleEvents[c_i];
				CircleEvent* ce = it->first;
				printf("\tTriplet (%d,%d,%d)\n", ce->points(0), ce->points(1), ce->points(2)); 
				if((ce->center - siteEvent->point).norm() < ce->radius) {
					printf("\tRemoving triplet: (%d,%d,%d)\n", ce->points(0),ce->points(1),ce->points(2));
					ce->falseAlarm = true;
				}
			}
			
			// Get the leaf information to check for circles
			vector <pair<int, AVL<TreeNode*>::Node*> > leafParents;
			avl.traversal_leaves(leafParents);
			printf("Traversal: {");
			vector <pair<int, TreeNode*> > sites;
			for(int i = 0; i < leafParents.size(); i++) {
				TreeNode* node = leafParents[i].second->value;
				int type = leafParents[i].first;
				if(type == 2) {
					printf("(%d,%d), ", node->p0i, node->p1i);
					sites.push_back(make_pair(node->p0i, node));
					sites.push_back(make_pair(node->p1i, node));
				}
				if(type == 0) {
					printf("%d, ", node->p0i);
					sites.push_back(make_pair(node->p0i, node));
				}
				if(type == 1) {
					printf("%d, ", node->p1i);
					sites.push_back(make_pair(node->p1i, node));
				}
			}
			printf("\b\b}\n");

			// Check for circles in triplets
			for(int s_i = 0; s_i < sites.size()-2; s_i++) {

				// Skip newly generated centers
				int i0 = sites[s_i].first, i1 = sites[s_i+1].first, i2 = sites[s_i+2].first;
				if(i0 == i2) continue;

				// If the bottom point of the fit circle can be tangent to the sweep line,
				// add it to the queue
				Vector2d center = fitCircle(data[i0], data[i1], data[i2]);
				double radius = (data[i0]-center).norm();
				double temp_y = center(1) - radius;
				printf("idx: %d, center: (%lf, %lf), temp_y: %lf\n", s_i, center(0), center(1), temp_y);
				printf("radius: %lf, sweepLine: %lf\n", radius, sweepLine);
				if(temp_y < sweepLine) { 

					if (allCircles.find(make_pair((CircleEvent*) NULL, center)) != allCircles.end()) {
						printf("\tTriplet (%d,%d,%d), (%lf, %lf) already exists.\n", i0, i1, i2, center(0), center(1));
						printf("all circles #: %lu\n", allCircles.size());
						continue;
					}

					// Create the circle event
					CircleEvent* ce = new CircleEvent();
					ce->point = Vector2d(center(0), temp_y);
					ce->points = Vector3i(i0,i1,i2);
					ce->center = center;
					ce->radius = radius;
					eventQueue.push(ce);
					allCircles.insert(make_pair(ce, ce->center));
					printf("\tAdding triplet: (%d,%d,%d), (%lf, %lf)\n", i0, i1, i2, center(0), center(1));

					// Register the circle event with the involved arcs
					sites[s_i].second->circleEvents.push_back(ce);
					sites[s_i+1].second->circleEvents.push_back(ce);
					sites[s_i+2].second->circleEvents.push_back(ce);
				}
				else printf("\tCircle already passed, not adding!\n");
			}

		}

		else {

			printf("\n--- circle ------------------------------------------------\n");

			// Update the sweepline
			CircleEvent* ce = dynamic_cast <CircleEvent*> (event);
			printf("circle event: point: (%lf, %lf), center:, (%lf, %lf), points: %d, %d, %d\n", ce->point(0), ce->point(1), ce->center(0), ce->center(1), 
				ce->points(0), ce->points(1), ce->points(2));
			sweepLine = ce->point(1) + 0.00001;
			printf("sweepLine: %lf\n", sweepLine);
			// avl.draw();
			getchar2();

			// Check if false alarm
			if(ce->falseAlarm || ce->falseAlarmCircle) {
				printf("\tFalse alarm!\n");
				continue;
			}

			// Get the arc that is disappearing due to the circle
			pair <bool, AVL<TreeNode*>::Node*> searchRes = 
				avl.search_candidateLoc(new TreeNode(ce->point, Vector2d(), true));
			assert(searchRes.second != NULL && "Could not find the above arc");
			TreeNode* node1 = searchRes.second->value;
			AVL<TreeNode*>::Node* searchNode = searchRes.second;
			printf("node1: (%d,%d)\n", node1->p0i, node1->p1i);

			// Fix node1 if next one is better
			AVL<TreeNode*>::Node* temp = avl.next(searchNode);
			AVL<TreeNode*>::Node* temp2 = avl.prev(searchNode);
			if(temp != NULL) printf("temp: '%s'\n", print(temp->value).c_str());
			if(temp != NULL) printf("temp2: '%s'\n", print(temp2->value).c_str());
			double diff1 = (node1->value() - ce->point(0));
			double diff2 = (temp == NULL) ? 1000.0 : (temp->value->value() - ce->point(0));
			double diff3 = (temp2 == NULL) ? 1000.0 : (temp2->value->value() - ce->point(0));
			printf("\t%lf vs %lf\n", diff1, diff2);
			if(fabs(diff2) < fabs(diff1)) {
				node1 = temp->value;
				searchNode = temp;
				printf("\t\tupdating node1 with temp\n");
			}
			printf("\t%lf vs %lf\n", diff1, diff3);
			if(fabs(diff3) < fabs(diff1)) {
				node1 = temp2->value;
				searchNode = temp2;
				printf("\t\tupdating node1 with temp2\n");
			}
			printf("node1: (%d,%d)\n", node1->p0i, node1->p1i);

			// Skip if the node can't be found
			double diff = (node1->value() - ce->point(0));
			if(fabs(diff) > 0.05) {
				printf("Skipping a circle event (node1) because it is behind the beach line\n");
				continue;
			}

			// Determine the other node
			AVL<TreeNode*>::Node* opt1 = avl.next(searchNode);
			if(opt1 != NULL) printf("opt1: '%s'\n", print(opt1->value).c_str());
			AVL<TreeNode*>::Node* opt2 = avl.prev(searchNode);
			if(opt2 != NULL) printf("opt2: '%s'\n", print(opt2->value).c_str());
			TreeNode* node2;
			if(opt1 == NULL) node2 = opt2->value;
			else if(opt2 == NULL) node2 = opt1->value;
			else {
				double diff1 = (node1->value() - opt1->value->value());	
				double diff2 = (node1->value() - opt2->value->value());	
				printf("diff1: %lf, diff2: %lf\n", diff1, diff2);
				if(fabs(diff1) < fabs(diff2)) node2 = opt1->value;
				else node2 = opt2->value;
			}

			// Skip if the node can't be found
			diff = (node2->value() - ce->point(0));
			if(fabs(diff) > 0.05) {
				printf("Skipping a circle event (node2) because it is behind the beach line\n");
				continue;
			}

			printf("node1: (%d,%d)\n", node1->p0i, node1->p1i);
			printf("node2: (%d,%d)\n", node2->p0i, node2->p1i);

			// Remove any potential circles that were going to use one of the break points for 
			// convergence that just got merged into a voronoi vertex.
			set <pair<CircleEvent*, Vector2d>, Vector2dComp>::iterator it =  allCircles.begin();
			int si0 = ce->points(0), si1 = ce->points(1), si2 = ce->points(2); 
			for(; it != allCircles.end(); it++) {
				CircleEvent* ce = it->first;
				int i0 = ce->points(0), i1 = ce->points(1), i2 = ce->points(2); 
				bool remove = false;
				if((i0 == si0 && i1 == si1) || (i1 == si0 && i2 == si1) || 
					(i0 == si1 && i1 == si0) || (i1 == si1 && i2 == si0)) remove = true; 
				if((i0 == si1 && i1 == si2) || (i1 == si1 && i2 == si2) || 
					(i0 == si2 && i1 == si1) || (i1 == si2 && i2 == si1)) remove = true; 
				
				if(remove) {
					printf("\tRemoving triplet: (%d,%d,%d)\n", i0, i1, i2);
					ce->falseAlarmCircle = true;
				}
			}
	
			// Remove the potential circle events from these nodes
			for(int ce_i = 0; ce_i < node1->circleEvents.size(); ce_i++) {
				CircleEvent* ce = node1->circleEvents[ce_i];
				if(ce->points[0] == node1->p0i && ce->points[1] == node1->p1i)
					ce->falseAlarmCircle = true;
				if(ce->points[1] == node1->p0i && ce->points[2] == node1->p1i)
					ce->falseAlarmCircle = true;
			}
			for(int ce_i = 0; ce_i < node2->circleEvents.size(); ce_i++) {
				CircleEvent* ce = node2->circleEvents[ce_i];
				if(ce->points[0] == node2->p0i && ce->points[1] == node2->p1i)
					ce->falseAlarmCircle = true;
				if(ce->points[1] == node2->p0i && ce->points[2] == node2->p1i)
					ce->falseAlarmCircle = true;
			}

			// Remove the arc from the tree
			printf("Before removes\n");
			getchar2();
			avl.remove(node1);
			// avl.draw();
			printf("Drawn after remove 1\n");
			getchar2();
			avl.remove(node2);
			// avl.draw();
			printf("Drawn after remove 2\n");
			getchar2();

			// Add the new break point 
			TreeNode* newNode;
			if(node1->p0i == node2->p1i)
				newNode = new TreeNode(node2->p0i, node1->p1i);
			else if(node1->p1i == node2->p0i)
				newNode = new TreeNode(node1->p0i, node2->p1i);
			else assert(false && "Unknown new break point creation");
			
 			avl.insert(newNode);
			printf("Inserted new node: '%s'\n", print(newNode).c_str());

			// Set the second points of the completed voronoi edges
			node1->edge1->p1 = ce->center;
			node1->edge2->p0 = ce->center;
			node2->edge1->p1 = ce->center;
			node2->edge2->p0 = ce->center;

			// Find angles around the cell center to place them ccw
			HalfEdge* e1 = node1->edge1, *e2 = node2->edge2;
			int site_idx = (node1->p0i == node2->p1i) ? node1->p0i : node1->p1i;
			Vector2d site = data[site_idx];
			Vector2d v1 = (0.5 * (e1->p0 + e1->p1) - site).normalized();
			Vector2d v2 = (0.5 * (e2->p0 + e2->p1) - site).normalized();
			double angle1 = atan2(v1(1), v1(0)) + (v1(1) < 0 ? 2*M_PI : 0);
			double angle2 = atan2(v2(1), v2(0)) + (v2(1) < 0 ? 2*M_PI : 0);
			if((angle1 < angle2) && fabs(angle1-angle2) > M_PI) angle1 += 2*M_PI;
			else if((angle2 < angle1) && fabs(angle2-angle1) > M_PI) angle2 += 2*M_PI;
			if(angle1 > angle2) {
				e1->prev = e2;
				e2->next = e1;
			}
			else {
				e2->prev = e1;
				e1->next = e2;
			}

			// Get the leaf information to check for circles again
			vector <pair<int, AVL<TreeNode*>::Node*> > leafParents;
			avl.traversal_leaves(leafParents);
			printf("Traversal: {");
			vector <pair<int, TreeNode*> > sites;
			for(int i = 0; i < leafParents.size(); i++) {
				TreeNode* node = leafParents[i].second->value;
				int type = leafParents[i].first;
				if(type == 2) {
					printf("(%d,%d), ", node->p0i, node->p1i);
					sites.push_back(make_pair(node->p0i, node));
					sites.push_back(make_pair(node->p1i, node));
				}
				if(type == 0) {
					printf("%d, ", node->p0i);
					sites.push_back(make_pair(node->p0i, node));
				}
				if(type == 1) {
					printf("%d, ", node->p1i);
					sites.push_back(make_pair(node->p1i, node));
				}
			}
			printf("\b\b}\n");

			// Check for circles in triplets
			for(int s_i = 0; s_i < sites.size()-2; s_i++) {

				// Skip newly generated centers
				int i0 = sites[s_i].first, i1 = sites[s_i+1].first, i2 = sites[s_i+2].first;
				if(i0 == i2) continue;

				// If the bottom point of the fit circle can be tangent to the sweep line,
				// add it to the queue
				Vector2d center = fitCircle(data[i0], data[i1], data[i2]);
				double temp_y = center(1) - (data[i0]-center).norm();
				printf("idx: %d, center: (%lf, %lf), temp_y: %lf\n", s_i, center(0), center(1), temp_y);
				if(temp_y < sweepLine) { 

					// Check if it existed before
					set <pair<CircleEvent*, Vector2d>, Vector2dComp>::iterator it =
						allCircles.find(make_pair((CircleEvent*) NULL, center));
					if(it != allCircles.end() && it->first->falseAlarmCircle){

						printf("\tTurning on an old false alarm for triplet: %d, %d, %d.\n", it->first->points(0), it->first->points(1), it->first->points(2));
						it->first->falseAlarmCircle = false;
						getchar2();
						continue;
					}
					else if(it == allCircles.end()) {

						// Create the circle event
						CircleEvent* ce = new CircleEvent();
						ce->point = Vector2d(center(0), temp_y);
						ce->points = Vector3i(i0,i1,i2);
						ce->center = center;
						eventQueue.push(ce);
						allCircles.insert(make_pair(ce, ce->center));
						printf("\tAdding triplet: (%d, %d, %d)\n", i0, i1, i2);

						// Register the circle event with the involved arcs
						sites[s_i].second->circleEvents.push_back(ce);
						sites[s_i+1].second->circleEvents.push_back(ce);
						sites[s_i+2].second->circleEvents.push_back(ce);
					}
				}

			}

			getchar2();
		}

		
	}
	
}
Example #28
0
void read_links(char * filename) {
	FILE * fptr = fopen(filename,"r");
	if (fptr==NULL) {
		cerr << "failed to open file" << endl;
		exit(1);
	}
	char buffer[5000];
	while (fgets(buffer,5000,fptr)) {
		if (buffer[0]=='#') {
			continue;
		}
		//chr1    59446789        +       chr1    59446926        +       13
		char chra[10];
		int ichra=-1;
		char stranda;
		unsigned long coorda;

		char chrb[10];
		int ichrb=-1;
		char strandb;
		unsigned long coordb;

		int support;


		int ret = sscanf(buffer,"%s\t%lu\t%c\t%s\t%lu\t%c\t%d",chra,&coorda,&stranda,chrb,&coordb,&strandb,&support);

		edge_info ei;

		ichra=to_chr(chra);
		ichrb=to_chr(chrb);

		if (ichra>24 || ichrb>24 || ichra==0 || ichrb==0) {
			cerr << " skipping link, chrM or chr?? " << endl;
			continue;
		}

		pos posa=pos(ichra,coorda);
		if (bps.find(posa)==bps.end()) {
			continue;
		}	
		pos posb=pos(ichrb,coordb);
		if (bps.find(posb)==bps.end()) {
			continue;
		}	

		//get the edge type
		int type=0;
		if (stranda=='+') {
			if (strandb=='+') {
				type=0;	
			} else {
				//negative
				type=2;
			}
		} else {
			if (strandb=='+') {
				type=3;
			} else {
				type=1;
			}
		}


		//get the normal support
		if (bp_support.find(posa)==bp_support.end() ) {
			cerr << "failed to find posa in bp_support " << endl;
		}
		if (bp_support.find(posb)==bp_support.end() ) {
			cerr << "failed to find posb in bp_support " << endl;
		}
		int normal=(bp_support[posa]+bp_support[posb])/4; //the lambda , average of two sites (2 copies each)
		int tumor=support;	

		edge e = edge(posa,posb,false);
		if (somatic_edges.find(e)!=somatic_edges.end() && somatic_edges[e].tumor>=ei.tumor) {
			//skip this already have a better one
			cerr << "SKipping edge " << buffer << endl;
			continue;
		}

		//set up the ei
		ei.length=0;
		ei.type=type;
		//cerr << posa.str() << " " << posb.str() << " " << normal << " " << tumor << endl;	
		ei.normal=normal;
		ei.tumor=tumor;
		ei.poisson();
		

		//put in the forward
		somatic_edges[e]=ei;

		//put in the reverse
		if (type<2) {
			type=1-type;
		}
		somatic_edges[e.reverse()]=ei;
		somatic_edges[e.reverse()].type=type;

		

		jump_edges[posa].insert(posb);
		jump_edges[posb].insert(posa);

		
	}
}
Example #29
0
inline void my_del(ll x, int index) {
	prt.erase(prt.find(PLI(x, index)));
	prt.erase(prt.find(PLI((x + g + r) % (g + r + g + r), index)));
}
Example #30
0
 BSONForEach( k, _keyPattern ) {
     if ( orderFields.find( k.fieldName() ) != orderFields.end() )
         return IndexDetails::HELPFUL;
 }