示例#1
0
void Universe::updateGeometry(atlas::utils::Time const &dt) {

	mTree = buildTree();
	Planet* mReferencePlanet;
	QuadTreeNode* mActualNode = mTree;

	for (int i = 0; i < numPlanets; i++) {
		mReferencePlanet = Planets[i];
		calculatePlanetsAcceleration(mReferencePlanet, mActualNode);
	}

	for (int i = 0; i < numPlanets; i++) {
		Planets[i]->updateGeometry(dt);
	}
	
	mTree->~QuadTreeNode();
}
 vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &dict) {
       vector<vector<string> > paths;
       vector<string> path(1, beginWord);
       if (beginWord == endWord){  //corner case;
             paths.push_back(path);
             return paths;
       }
       unordered_set<string> forward, backward;
       forward.insert(beginWord);
       backward.insert(endWord);
       unordered_map<string, vector<string>> tree;
       //make sure the tree generating direction is consistent, since we have to start from the smaller set to accelerate;
       bool reversed = false; 
       if (buildTree(forward, backward, dict, tree, reversed))
       	getPath(beginWord, endWord, tree, path, paths);
       return paths;
 }
示例#3
0
//
// Stage 0: Check if it is a Msg. This is deleted by Msg::deleteMsg( ObjId )
// Stage 1: mark for deletion. This is done by setting cinfo = 0
// Stage 2: Clear out outside-going msgs
// Stage 3: delete self and attached msgs, 
void Neutral::destroy( const Eref& e, int stage )
{
	if ( e.element()->cinfo()->isA( "Msg" ) ) {
		Msg::deleteMsg( e.objId() );
		return;
	}
	vector< Id > tree;
	Eref er( e.element(), ALLDATA );
	unsigned int numDescendants = buildTree( er, tree );
	/*
	cout << "Neutral::destroy: id = " << e.id() << 
		", name = " << e.element()->getName() <<
		", numDescendants = " << numDescendants << endl;
		*/
	assert( numDescendants == tree.size() );
	Element::destroyElementTree( tree );
}
示例#4
0
bool RegressionTree::train_(RegressionData &trainingData){
    
    //Clear any previous model
    clear();
    
    const unsigned int M = trainingData.getNumSamples();
    const unsigned int N = trainingData.getNumInputDimensions();
    const unsigned int T = trainingData.getNumTargetDimensions();
    
    if( M == 0 ){
        Regressifier::errorLog << "train_(RegressionData &trainingData) - Training data has zero samples!" << std::endl;
        return false;
    }
    
    numInputDimensions = N;
    numOutputDimensions = T;
    inputVectorRanges = trainingData.getInputRanges();
    targetVectorRanges = trainingData.getTargetRanges();
    
    //Scale the training data if needed
    if( useScaling ){
        //Scale the training data between 0 and 1
        trainingData.scale(0, 1);
    }
    
    //Setup the valid features - at this point all features can be used
    Vector< UINT > features(N);
    for(UINT i=0; i<N; i++){
        features[i] = i;
    }
    
    //Build the tree
    UINT nodeID = 0;
    tree = buildTree( trainingData, NULL, features, nodeID );
    
    if( tree == NULL ){
        clear();
        Regressifier::errorLog << "train_(RegressionData &trainingData) - Failed to build tree!" << std::endl;
        return false;
    }
    
    //Flag that the algorithm has been trained
    trained = true;
    
    return true;
}
示例#5
0
/**************************************************
 * This function opens the file and reads each    *
 * line into the buildArray function. It then     *
 * calls the rest of the functions to sort the    *
 * array and build the balanced binary tree.      *
 * EXIT 2 for file input error                    *
 * EXIT 1 for memory error                        *
 **************************************************/
void initialize(char *filename)
{
    FILE *fp;
    char buffer[21], **names;
    int count = 0, *count_ptr = &count, size = 2, *size_ptr = &size;
    BNODE* root;

    if ((fp = fopen(filename, "r")) == NULL)
    {
        printf("Error: Filename does not exist\n");
        exit(2);
    }
    
    if ((names = malloc(2 * sizeof(char*))) == NULL)
    {
        printf("Error: Unable to allocate memory\n");
        exit(1);
    }

    while (fgets(buffer, sizeof(buffer), fp) != NULL)
    {
        /* Double the size of the array after it is full */
        if (count == size)
            names = resizeArray(names, size_ptr);

        names = buildArray(names, buffer, count_ptr);
    }

    fclose(fp);

    names = sortArray(names, count_ptr);

    root = buildTree(names, 0, count-1);

    printf("\n preorder: ");
    preorder(root);
    printf("\n\n");

    printf("  inorder: ");
    inorder(root);
    printf("\n\n");

    printf("postorder: ");
    postorder(root);
    printf("\n");
}
示例#6
0
void genHash(char file[])
{
	mdstr *a;
	char term[KEYSIZE]; // max chars in word
	FILE *fp;
	
	fp = fopen(file,"r+");
		
	if(!fp)
		printf("--Unable to open file: %s--\n\n",file);
	else
	{
		//printf("opened");
		doc_len = 0;
		while(fscanf(fp,"%s",term) != EOF) //Read word by word in file	
		{
			/*
				Do Stemming Optimization
			*/
			
			if(isSW(term)) continue;

			term[strlen(term)]='\0';
			doc_len++;

			a = (mdstr *)do_test(term);//finding md5 hash
			strcpy(g_hex,"\0");
			strcpy(g_hex,a->hash);
			g_hex[32]='\0';
			free(a);

			//printf("Hex value: %s",g_hex);
			strcpy(g_key,"\0");
			strcpy(g_key,term);
			g_key[strlen(g_key)]='\0';
			toBinary();//hash2Bin();
			
			buildTree();
			
		}
		printf("Finished Indexing %s\n",g_ifile);
		fclose(fp);

	}
}
示例#7
0
文件: KdTree.hpp 项目: lieff/GIGL
 KdTree<Primitive>::KdTree(const std::vector<Primitive>& primitives, const int inters_cost,
                           const int trav_cost, const int max_depth, const uint min_num_prims,
                           const float empty_bonus): m_max_depth{max_depth}, m_actual_depth{0},
                           m_min_num_prims{glm::max(min_num_prims, 1u)},
                           m_avg_prims_per_leaf{0.0f}, m_inters_cost{inters_cost},
                           m_trav_cost{trav_cost}, m_empty_bonus{empty_bonus},
                           m_next_node_id{0}, m_n_alloc_nodes{0}, m_leaf_count{0},
                           m_prims{primitives.data()} {
     const uint n{static_cast<uint>(primitives.size())};
     if (m_max_depth < 0) {
         // Maximal depth = 8 + 1.3 * log2(n)
         m_max_depth = static_cast<int>(8 + 1.3f * log2f(static_cast<float>(n)));
     }
     printInfo("Constructing k-d tree for %u primitives.", n);
     printInfo("Maximal tree depth: %i.", m_max_depth);
     const auto t_begin = HighResTimer::now();
     // Reserve memory
     m_prim_boxes = new BBox[n];
     uint* prims_bottom{new uint[n]};
     uint* prims_top{new uint[n * (m_max_depth + 1)]};
     for (auto axis = 0; axis < 3; ++axis) { m_edges[axis] = new BoundEdge[2 * n]; }
     // Each primitive overlaps the root node
     for (uint i = 0; i < n; ++i) {
         prims_bottom[i] = i;
         m_prim_boxes[i] = m_prims[i].computeBBox();
         m_tree_box.extend(m_prim_boxes[i]);
     }
     // Recursively build the tree
     buildTree(0, m_tree_box, prims_bottom, n, 0, 0, prims_bottom, prims_top);
     // Cleaning up
     m_nodes.resize(m_next_node_id);
     m_nodes.shrink_to_fit();
     for (auto axis = 0; axis < 3; ++axis) { delete[] m_edges[axis]; }
     delete[] prims_top;
     delete[] prims_bottom;
     delete[] m_prim_boxes;
     // Compute and print statistics
     m_avg_prims_per_leaf /= m_leaf_count;
     const auto t_diff = HighResTimer::now() - t_begin;
     const auto t_us   = std::chrono::duration_cast<std::chrono::microseconds>(t_diff).count();
     printInfo("k-d tree construction complete after %.2f ms.", t_us * 0.001f);
     printInfo("Actual tree depth: %i.", m_actual_depth);
     printInfo("Average number of primitives per leaf: %.2f.", m_avg_prims_per_leaf);
     printInfo("k-d tree consists of %u nodes.", m_next_node_id);
 }
void TestASTMatcher::testMatchSubTree()
{	
	CPPUNIT_ASSERT_EQUAL(true, matcher.matchSubTree(NULL, NULL));
	CPPUNIT_ASSERT_EQUAL(true, matcher.matchSubTree(testNode, NULL));
	CPPUNIT_ASSERT_EQUAL(false, matcher.matchSubTree(NULL, testNode));

	ASTNode* node = buildTree();
	CPPUNIT_ASSERT_EQUAL(true, matcher.matchSubTree(testNode, node));

	node = buildSubTree();
	CPPUNIT_ASSERT_EQUAL(true, matcher.matchSubTree(testNode, node));

	node = buildSubTreeWithDiffValue();
	CPPUNIT_ASSERT_EQUAL(false, matcher.matchSubTree(testNode, node));

	node = buildSubTreeWithDiffStruct();
	CPPUNIT_ASSERT_EQUAL(false, matcher.matchSubTree(testNode, node));
}
示例#9
0
void Expression::compileExpression( const QString & expression )
{
	// Make a tree to put the expression in.
	BTreeBase *tree = new BTreeBase();
	BTreeNode *root = new BTreeNode();

	// parse the expression into the tree
	buildTree(expression,tree,root,0);
	// compile the tree into assembly code
	tree->setRoot(root);
	tree->pruneTree(tree->root());
	traverseTree(tree->root());
	
	// Note deleting the tree deletes all nodes, so the root
	// doesn't need deleting separately.
	delete tree;
	return;
}
示例#10
0
int main(int argc, const char * argv[]) {
    
    std::vector<int> v;
    
    v.push_back(1);
    v.push_back(2);
    v.push_back(4);
    v.push_back(7);
    v.push_back(8);
    v.push_back(11);
    v.push_back(13);
    
    
    node<int> *head = buildTree(v, 0, 6);
    
    printTree(head);
    return 0;
}
示例#11
0
void OutlineTree::buildTree( QListViewItem *parentItem, const QDomElement &parentElement )
{
    QListViewItem *thisItem = 0;
    QDomNode node = parentElement.firstChild();
    while ( !node.isNull() ) {
	if ( node.isElement() && node.nodeName() == "outline" ) {
	    // add a new list view item for the outline
	    if ( parentItem == 0 )
		thisItem = new QListViewItem( this, thisItem );
	    else
		thisItem = new QListViewItem( parentItem, thisItem );
	    thisItem->setText( 0, node.toElement().attribute( "text" ) );
	    // recursive build of the tree
	    buildTree( thisItem, node.toElement() );
	}
	node = node.nextSibling();
    }
}
示例#12
0
int main(void)
{
	scanf("%d %d", &N, &Q);
	for (unsigned i = 0; i != N; ++i)
	{
		scanf("%d", &val[i]);
	}
	buildTree(0, N - 1, 0);
	for (unsigned i = 0; i != Q; ++i)
	{
		int a, b;
		scanf("%d %d", &a, &b);
		traverse(a - 1, b - 1, 0);
		printf("%d\n", maxVal - minVal);
		maxVal = 0;
		minVal = 1 << 30;
	}
}
示例#13
0
KdTreeAccel::KdTreeAccel(const vector<Shape*> &prims, int md, int mp,
	Float eb) : maxDepth(md), maxPrims(mp), emptyBonus(eb)
{
	int np = prims.size();
	primitives = prims;
	//Initialize tree depth
	if (maxDepth <= 0)
	{
		maxDepth = roundToInt(8 + 1.3 * logToInt(static_cast<Float>(np)));
	}
	// If no node in vector, terminate initialization
	if (np == 0)
	{
		root = nullptr;
		return;
	}
	//Initialize bouding box for all primitives in stack
	for (int i = 0; i < np; ++i)
	{
		treeBound.Union(prims[i]->ObjBound);
	}
	//Allocate bound edge info
	BoundEdge* edges[3];
	for (int i = 0; i < 3; ++i)
	{
		edges[i] = new BoundEdge[np * 2];
	}
	//Create stack to record primitive indices
	vector<int> primNum(np);
	for (int i = 0; i < np; ++i)
	{
		primNum[i] = i;
	}
	//Start recursively build the tree
	root = new KdAccelNode;
	buildTree(root, treeBound, primNum, maxDepth, edges);

	//Clean data
	for (int i = 0; i < 3; ++i)
	{
		delete[] edges[i];
		edges[i] = nullptr;
	}
}
// This function is finding the right thing to do based on the time that we are in
void doTheScripting(long itime)
{	
	while (itime >= sceneStartTime + sceneDuration)
	{
		sceneStartTime += sceneDuration;
		sceneNumber++;
	}

	int sceneID = sceneNumber; // That's the easiest thing, really
	int sceneTime = itime - sceneStartTime;

	// Create the stuff based on the current timing thing
	transformationSeed = sceneID;
	createTransforms((float)sceneTime / 44100.0f);
	buildTree();
	generateParticles();
	transformationSeed = sceneID;
	generateOGLTransforms((float)sceneTime / (float)sceneDuration);
}
示例#15
0
void ShareManager::addDirectory(const string& realPath, const string& virtualName) {
	if(realPath.empty() || virtualName.empty()) {
		throw ShareException(_("No directory specified"));
	}

	if (!checkHidden(realPath)) {
		throw ShareException(_("Directory is hidden"));
	}

	if(Util::stricmp(SETTING(TEMP_DOWNLOAD_DIRECTORY), realPath) == 0) {
		throw ShareException(_("The temporary download directory cannot be shared"));
	}

	{
		Lock l(cs);

		for(auto& i: shares) {
			if(Util::strnicmp(realPath, i.first, i.first.length()) == 0) {
				// Trying to share an already shared directory
				throw ShareException(_("Directory already shared"));
			} else if(Util::strnicmp(realPath, i.first, realPath.length()) == 0) {
				// Trying to share a parent directory
				throw ShareException(_("Remove all subdirectories before adding this one"));
			}
		}
	}

	HashManager::HashPauser pauser;

	auto dp = buildTree(realPath);

	string vName = validateVirtual(virtualName);
	dp->setName(vName);

	Lock l(cs);

	shares[realPath] = move(vName);

	merge(dp, realPath);

	rebuildIndices();
	setDirty();
}
示例#16
0
void runProvider(int argc, char **argv)
{
   int port;

   ember_init(onThrowError, onFailAssertion, malloc, free);
   initializePpmStreams();
   buildTree(&_root);

   if(argc >= 2)
   {
      port = atoi(argv[1]);

      printf_s("accepting client on port %d\n", port);
      acceptClient(port);
   }

   sampleNode_free(&_root);
   freePpmStreams();
}
示例#17
0
int main(){
	int frequencies[UniqueSymbols] = {0};
	const char *ptr = SampleString;
	while (*ptr != '\0')
		++frequencies[*ptr++];

	iNode *root = buildTree(frequencies);

	HuffCodeMap codes;
	generateCodes(root, HuffCode(), codes);
	delete root;

	for (HuffCodeMap::const_iterator it = codes.begin(); it != codes.end(); it++){
		std::cout << it->first << " ";
		std::copy(it->second.begin(), it->second().end(), std::ostream_iterator<bool>(std::cout));
		std::cout << std::endl;
	}
	return 0;
}
int main() {
    int nStudents,nInstructs;
    while(~scanf("%d%d",&nStudents,&nInstructs)) {
//        for(int i=1; i<=nStudents; i++)
//            scanf("%d",&arr[i]);
        buildTree(1,1,nStudents);
        //puts("..");
        char ch;
        int i,j;
        while(nInstructs--) {
            scanf("%c %d%d",&ch,&i,&j);
            getchar();
           // printf("ch = %c i = %d j = %d\n",ch,i,j);
            if(ch == 'Q') printf("%d\n",query(1,i,j));
            if(ch == 'U') update(1,i,j);
        }
    }
    return 0;
}
示例#19
0
void PluginDialog::replyFinished(QNetworkReply *reply)
{
    QString replyText = reply->readAll();
    if(reply->error() != QNetworkReply::NoError)
    {
        //Parse servers response
        QDomDocument doc("error");
        if (!doc.setContent(replyText)) {
            //No XML to parse, user is probably disconnected
            return;
        }else
        {
            QDomElement docElem = doc.documentElement();
            QDomElement message = docElem.firstChildElement("message");
            if(!message.text().isEmpty())
            {
                WARNING("Failed to get plugin list from server. Error was: " + message.text());
                QMessageBox::warning(this, "Failed to get plugin list", "Failed to get plugin list from server.\nError was: " + message.text());
            }
        }
    }else
    {
        //No error in request
        addDefaultNodes();
        QDomDocument doc("response");
        if(!doc.setContent(replyText))
        {
            WARNING("Failed to get plugin list from " + reply->request().url().toString() + ".\n Failed to parse reply as XML");
            QMessageBox::warning(this, "Failed to get plugin list", "Failed to get plugin list from " + reply->request().url().toString() + ". Failed to parse reply as XML.");
        }
        QDomElement docElem = doc.documentElement();
        QDomNode pluginNode = docElem.firstChild();
        while(!pluginNode.isNull())
        {
            parsePluginNode(pluginNode);
            pluginNode = pluginNode.nextSibling();
        }
        //Show the plugins in the tree
        stdModel.removeRow(0);
        buildTree();
    }
}
示例#20
0
RWSegmentVector::RWSegmentVector(AbstractGenPointChain<int>& aChain,
				 double minDeviation) 
{
  if (aChain.empty())
    {
      return;  // Nothing to do
    }

  // Convert chain to a vector of points

  vector<Point> myChain;
  aChain.setToBegin();

  while (!aChain.isAtEnd())
    {
      myChain.push_back(aChain.accessCurrent());
      aChain.moveNext();
    }

  // Build the tree
  _root = buildTree(myChain, 0, (myChain.size() - 1), minDeviation);

  // And now, construct the vector of Segments we want to retrieve
  if (_root != 0)
    {
      addSegmentIfTerminalNode(_root, myChain);
    }

  // Post-processing : Can we simplify?
  // Based on an idea by Rosin and West...
  // *** WAIT AND SEE ***
  
  // Delete auxiliary data structures
  if (_root != 0)
    {
      delete _root;
    }

  _indexes.erase(_indexes.begin(), _indexes.end());
//  _significance.erase(_significance.begin(), _significance.end());
}
 vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
     vector<vecStr> result;
     vecStr path(1,beginWord);
     if(beginWord==endWord){
         result.push_back(path);
         return result;
     }
     end=endWord;
     //双向bfs
     setStr begin;
     setStr end;
     begin.insert(beginWord);
     end.insert(endWord);
     setStr words(wordList);
     mapStr2VecStr tree;
     bool flip=false;
     if(buildTree(begin,end,words,tree,flip))//双向bfs
         //output
         getPath(result,path,tree,beginWord);//dfs得到答案
     return result;
 }
示例#22
0
bool restoringTest(const vector<int>& bfs, const vector<int>& dfs) {
	Tree tree = buildTree(bfs, dfs);
	cout << tree;
	Tree::Iterator dfsIterator = tree.getDFSIterator();
	Tree::Iterator bfsIterator = tree.getBFSIterator();
	vector<int> bfsTraverse, dfsTraverse;
	while(true) {
		if(*dfsIterator < 0) break;
		bfsTraverse.push_back(*bfsIterator);
		dfsTraverse.push_back(*dfsIterator);
		dfsIterator++;
		bfsIterator++;
	}

	cout << "new bfs: ";
	p_v(bfsTraverse);
	cout << "new dfs: ";
	p_v(dfsTraverse);

	return (bfs == bfsTraverse) && (dfs == dfsTraverse);
}
示例#23
0
/*---------------------------------------------------------------------
  Iterate through the contents of the 'buffer' argument and record the 
  frequency of each byte, then sort the dataList of bytes by their 
  frequencies and remove the bytes with 0 occurrences from the list.
  ---------------------------------------------------------------------*/
void Huffman::countBytes(const unsigned char* const buffer, long bufferSize)
{
	if(!countedOnce)
	{
		for(int i = 0; i < bufferSize; ++i)
			dataList[(int)buffer[i]].getValue().Increment();

		countedOnce = true;
	}
	//sort the results
	std::sort(dataList.begin(), dataList.end());
	//purge the zeros from the data list
	for(std::vector<ByteData>::iterator itr = dataList.begin(); itr != dataList.end(); ++itr)
		if(itr->getValue().getFrequency() == 0)
		{
			dataList.erase(itr, dataList.end());
			break;
		}
	//build the Huffman tree
	buildTree();
}
示例#24
0
Tree::Tree(int frequencia[], bool compress){
    if(compress == true){
        lista = new ArrayList();
        codeNodes = new string[256];
        aux = 0;
        sizeTree = 0;
        tree_written.clear();
        buildTree(frequencia);
    }
    else{
        root = new Node(0,false);
        tree_written.clear();
        sizeTree = 0;
        aux = 0;
        sizeHeader = 0;
        sizeLast = 0;
        sizeFileName = 0;
        sizeTrash = 0;
        filename.clear();
    }
}
int main(int argc, char *argv[])
{
    FILE *in = fopen("btree.in", "r");
    char t[MAX_NODES + 1][MAX_WORD_SIZE + 1];
    
    // Silencing valgrind
    memset(t, 0, sizeof(t));
    int n = buildTree(in, t, 1);
    int m;
    
    printf("The pre-order traversal is: ");
    preOrder(t, 1, n);
    printf("\n\n");
    
    printf("The in-order traversal is: ");
    inOrder(t, 1, n);
    printf("\n\n");
    
    printf("The post-order traversal is: ");
    postOrder(t, 1, n);
    printf("\n\n");
    
    printf("The array content is as follows:\n");
    
    for (m = 0; m <= n; m++) {
        printf("%4s ", t[m]);
    }
    
    printf("\n");
    
    for (m = 0; m <= n; m++) {
        printf("%4d ", m);
    }
    
    printf("\n\n");
    
    fclose(in);
    
    return 0;
}
示例#26
0
// main func
int main(int argc, char *argv[]) {
	// parse command line arguments
	// -c -cpp -py -cs -lua : enable only the languages
	if ( argc > 1 ) {
		config.generateCpp=false;
		config.generateC=false;
		config.generatePy=false;
		config.generateCs=false;
		config.generateLua=false;
	}
	for (int pnum=1; pnum < argc; pnum++) {
		if ( strcmp(argv[pnum],"-c") == 0 ) config.generateC=true;
		else if ( strcmp(argv[pnum],"-cpp") == 0 ) config.generateCpp=true;
		else if ( strcmp(argv[pnum],"-cs") == 0 ) config.generateCs=true;
		else if ( strcmp(argv[pnum],"-py") == 0 ) config.generatePy=true;
		else if ( strcmp(argv[pnum],"-lua") == 0 ) config.generateLua=true;
	}
	TCODList<char *> files=TCODSystem::getDirectoryContent("include", "*.hpp");
	// hardcoded index page
	char tmp[128];
	root = new PageData();
	root->name=(char *)"index2";
	root->title=(char *)"Index";
	root->pageNum=(char *)"";
	root->breadCrumb=(char *)"<a onclick=\"link('index2.html')\">Index</a>";
	root->url=(char *)"doc/index2.html";
	sprintf(tmp,"The Doryen Library v%s - table of contents",TCOD_STRVERSION);
	root->desc=strdup(tmp);
	// parse the *.hpp files
	for ( char **it=files.begin(); it != files.end(); it++) {
		char tmp[128];
		sprintf(tmp,"include/%s",*it);
		parseFile(tmp);
	} 	
	// computations
	buildTree();
	// html export
	genDoc();
}
示例#27
0
Tree::Tree(QByteArray Rep)
{
    this->Code.clear();
    this->Mcode = 0;
    this->Rpt.clear();
    for (int i = 0; i < Rep.size() ; ++i)
    {
        if( Rep.at(i) == (uchar)('!')  )
        {
            this->Rpt.push_back(Pub( Rep.at(i+1), true ));
            ++i;
        }
        else
        {
            if( Rep.at(i) == (uchar)('*')  ) this->Rpt.push_back( Pub( Rep.at(i), false ) );
            else this->Rpt.push_back( Pub( Rep.at(i), true ) );
        }
    }
    QVector<bool> Enc;
    Enc.clear();
    this->Root = buildTree(Enc);
}
示例#28
0
int main(int argC,char* argV[]){
	int i;
	tree t;
	
	if(argC==1)
		printf("Usage : %s <RPN expression enclosed by quotes> <optional parameter to trace the build process>",argV[0]);
	else{
		buildStack(argV[1]);
		
		if(checkRPN()==0){
			printf("\nInvalid RPN !");
			return 0;
		}
		
		t = buildTree(getNextString(),argV[2]);
		
		printf("\nFinal infix expression : ");
		inorder(t);
	}
	
	return 0;
}
示例#29
0
// ---------------------------------------------------------------------------------------
// This function inserts a new color into the list.
// If the color is already present in the list it will throw an exception.
// It can be modified to update the weight if the entry already exists
// ---------------------------------------------------------------------------------------
void
RandomColorByWeight::insertColors(const std::vector<std::pair<std::string, uint32_t>>& colorsVec)
{
    for (auto colorEntry : colorsVec)
    {
        auto itrColor = _colorsMap.find(colorEntry.first);

        // entry is already present in the list. Throw an exception
        if (itrColor != _colorsMap.end())
        {
            throw std::invalid_argument("Error Inserting Color. Duplicate Entry: \"" + colorEntry.first + "\"");
        }

        // Create a color Node and insert that into the map with
        // Key: ColorName
        // Value: Pointer to ColorNode
        _colorsMap.insert(make_pair(colorEntry.first,
                                    std::shared_ptr<ColorNode>
                                    (new ColorNode(colorEntry.first, colorEntry.second))));
    }

    buildTree();
}
示例#30
0
int main(void){
	int i;

	scanf("%d", &N);

	for (i = 1; i < N; i++){
		int a, b;
		scanf("%d %d", &a, &b);
		addEdge(a,b,graph,&nextEdge,start);
		addEdge(b,a,graph,&nextEdge,start);
	}

	for (i = 1; i <= N; i++)
		scanf("%lld", &value[i]);

	buildTree(1,-1);

	countSteps(1);

	printf("%lld\n", increment[1] + decrement[1]);

	return 0;
}