/**
     * @param n an integer
     * @param m an integer
     * @param operators an array of point
     * @return an integer array
     */
    vector<int> numIslands2(int n, int m, vector<Point> &operators) {
        b.clear();
        dj.clear();

        this->n = n;
        this->m = m;
        b.resize(n * m, false);
        dj.resize(n * m);

        int i;
        for (i = 0; i < n * m; ++i) {
            dj[i] = i;
        }

        int cc = 0;
        int x, y;
        int x1, y1;
        int r, r1;
        vector<int> ans;
        vector<int> adj;
        int j;
        for (i = 0; i < operators.size(); ++i) {
            x = operators[i].x;
            y = operators[i].y;
            if (b[x * m + y]) {
                ans.push_back(cc);
                continue;
            }
            b[x * m + y] = true;
            adj.clear();
            for (j = 0; j < 4; ++j) {
                x1 = x + d[j][0];
                y1 = y + d[j][1];
                if (inbound(x1, y1) && b[x1 * m + y1]) {
                    adj.push_back(x1 * m + y1);
                }
            }
            if (adj.empty()) {
                ans.push_back(++cc);
                continue;
            }
            dj[findRoot(adj[0])] = findRoot(x * m + y);
            for (j = 1; j < adj.size(); ++j) {
                r = findRoot(x * m + y);
                r1 = findRoot(adj[j]);
                if (r != r1) {
                    dj[r1] = r;
                    --cc;
                }
            }
            ans.push_back(cc);
        }
        return ans;
    }
Ejemplo n.º 2
0
 inline static
 LabelT set_union(LabelT *P, LabelT i, LabelT j){
     LabelT root = findRoot(P, i);
     if(i != j){
         LabelT rootj = findRoot(P, j);
         if(root > rootj){
             root = rootj;
         }
         setRoot(P, j, root);
     }
     setRoot(P, i, root);
     return root;
 }
Ejemplo n.º 3
0
void C_WeightedQuickUnion::connect(unsigned int inx1, unsigned int inx2) {
    unsigned int inx_root_1 = findRoot(inx1);
    unsigned int inx_root_2 = findRoot(inx2);

    if (inx_root_1 == inx_root_2) return;

    if (treeWeights[inx_root_1] > treeWeights[inx_root_2]){
        IDs_raw_ptr->at(inx_root_2) = inx_root_1;
        treeWeights[inx_root_1] += treeWeights[inx_root_2];
    } else {
        IDs_raw_ptr->at(inx_root_1) = inx_root_2;
        treeWeights[inx_root_2] += treeWeights[inx_root_1];
    }
}
Ejemplo n.º 4
0
int height(std::vector<std::unordered_set<int>> &children,
  const std::vector<int> parents)
{
  int root = findRoot(parents);

  std::vector<int> leaves = findLeaves(children),
    subtreeHeight(parents.size(), 1);

  while (!leaves.empty()) {
    std::vector<int> newLeaves;
    for (int nextLeaf: leaves) {
      int nextParent = parents.at(nextLeaf);
      if (nextParent == -1) {
        continue;
      }

      subtreeHeight[nextParent] = subtreeHeight[nextLeaf] + 1;

      children[nextParent].erase(nextLeaf);
      if (children[nextParent].empty()) {
        newLeaves.push_back(nextParent);
      }
    }
    leaves = newLeaves;
  }

  return subtreeHeight[root];
}
Ejemplo n.º 5
0
int findRoot(int tree[], int n) {
	if (tree[n] == -1) return n;
	else {
		tree[n] = findRoot(tree, tree[n]);
		return tree[n];
	}
}
Ejemplo n.º 6
0
const Real GreensFunction2DAbs::drawTheta(const Real rnd,
                                          const Real r,
                                          const Real t) const
{
    THROW_UNLESS(std::invalid_argument, 0.0<=rnd && rnd <= 1.0);

    if(rnd == 1e0)
        return 2e0 * M_PI;

    if(fabs(r) < CUTOFF)// r == 0e0 ?
    {
        throw std::invalid_argument(
                (boost::format("2DAbs::drawTheta r is too small: r=%f10") % r).str());
    }

    if(fabs(r-a) < CUTOFF)// r == a ?
    {
        //when R equal a, p_int_theta is zero at any theta
        throw std::invalid_argument(
                (boost::format("2DAbs::drawTheta r is nealy a: r=%f10, a=%f10") % r % a).str());
    }

    if(t == 0e0 || D == 0e0)
        return 0e0;

    Real int_2pi = p_int_2pi(r, t);

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * When t is too large, int_2pi become zero and drawR returns 2pi    *
     * at any value of rnd. To avoid this,  return rnd * theta / 2pi     *
     * because when t -> \infty the probability density function of theta*
     * become uniform distribution                                       *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    if(int_2pi == 0e0)
    {
        std::cout << dump();
        std::cout << "Warning: t is too large. t = " << t << std::endl;
    }

    p_theta_params params = {this, t, r, rnd * int_2pi};

    gsl_function F =
    {
        reinterpret_cast<double (*)(double, void*)>(&p_theta_F), &params
    };

    const Real low(0e0);
    const Real high(2e0 * M_PI);

    const gsl_root_fsolver_type* solverType(gsl_root_fsolver_brent);
    gsl_root_fsolver* solver(gsl_root_fsolver_alloc(solverType));

    const Real theta(findRoot(F, solver, low, high, 1e-18, 1e-12,
                              "GreensFunction2DAbsSym::drawTheta"));

    gsl_root_fsolver_free(solver);

    return theta;
}
Ejemplo n.º 7
0
const Real GreensFunction2DAbs::drawTime(const Real rnd) const
{
    THROW_UNLESS(std::invalid_argument, 0.0<=rnd && rnd <= 1.0);
    if(D == 0e0 || a == std::numeric_limits<Real>::infinity() || rnd == 1e0)
        return std::numeric_limits<Real>::infinity();
    if(a == r0 || rnd == 0e0)
        return 0e0;

    p_survival_params params = {this, rnd};

    gsl_function F = 
    {
        reinterpret_cast<double (*)(double, void*)>(&p_survival_F), &params
    };

    // this is not so accurate because
    // initial position is not the center of this system.
    const Real t_guess(a * a * 0.25 / D);
    Real value(GSL_FN_EVAL(&F, t_guess));
    Real low(t_guess);
    Real high(t_guess);

    // to determine high and low border
    if(value < 0.0)
    {
        do
        {
            high *= 1e1;
            value = GSL_FN_EVAL(&F, high);
            if(fabs(high) > t_guess * 1e6)
                throw std::invalid_argument("could not adjust higher border");
        }
        while(value <= 0e0);
    }
    else
    {
        Real value_prev = value;
        do
        {
            low *= 1e-1;
            value = GSL_FN_EVAL(&F, low);
            if(fabs(low) <= t_guess * 1e-6 || fabs(value - value_prev) < CUTOFF)
                throw std::invalid_argument("could not adjust lower border");
            value_prev = value;
        }
        while(value >= 0e0);
    }

    //find the root
    const gsl_root_fsolver_type* solverType(gsl_root_fsolver_brent);
    gsl_root_fsolver* solver(gsl_root_fsolver_alloc(solverType));

    const Real t(findRoot(F, solver, low, high, 1e-18, 1e-12,
                          "GreensFunction2DAbs::drawTime"));

    gsl_root_fsolver_free(solver);

    return t;
}
void mergeClusters(int e1,int e2)
{
    int root1 = findRoot(e1);
    int root2 = findRoot(e2);

    if(root1 > root2)
    {
        clusters[root2] = root1;
        size[root1]+=size[root2];
    }
    else
    {
        clusters[root1] = root2;
        size[root2]+=size[root1];
    }
    nClusters--;
}
Ejemplo n.º 9
0
void DisjointSet::setUnion(const uint elementA, const uint elementB) {
	int rootA, rootB;

	rootA = findRoot(elementA);
	rootB = findRoot(elementB);

	if ( (rootA == -1) || (rootB == -1) || (rootA == rootB) )
		return;

	if (m_sets[rootA] <= m_sets[rootB]) {
		m_sets[rootA] += m_sets[rootB];
		m_sets[rootB] = rootA;
	}
	else {
		m_sets[rootB] += m_sets[rootA];
		m_sets[rootA] = rootB;
	}
}
Ejemplo n.º 10
0
           void unite(int x, int y) {

                x = findRoot( x ); 

                y = findRoot( y ); 

                if(x == y) return;

                if( depth[ x ] < depth[ y ]) {

                    root[ x ] = y;

                } else {

                    root[ y ] = x;
                }

                if(depth[ x ] == depth[ y ]) depth[ y ]++;
           };
Ejemplo n.º 11
0
 bool check(vector<vector<int>>& edges, int omitIndex) {
     memset(parent, -1, sizeof(parent));
     memset(treeParent, -1, sizeof(treeParent));
     for (int i = 0; i < edges.size(); ++i) {
         if (i == omitIndex) continue;
         auto& v = edges[i];
         int root1 = findRoot(v[0]);
         int root2 = findRoot(v[1]);
         if (root1 == root2) {
             return false;
         }
         parent[root1] = root2;
         if (treeParent[v[1]] != -1) {
             return false;
         }
         treeParent[v[1]] = v[0];
     }
     return true;
 }
Ejemplo n.º 12
0
int findRoot(int x){
	if (Tree[x]==-1)
	{
		return x;
	}else{
		int tmp=findRoot(Tree[x]);
		Tree[x]=tmp;
		return tmp;
	}
}
Ejemplo n.º 13
0
void Tree::print(ostream& out, string mode) {
	try {
		int root = findRoot();
		printBranch(root, out, mode);
		out << ";" << endl;
	}
	catch(exception& e) {
		m->errorOut(e, "Tree", "print");
		exit(1);
	}
}
Ejemplo n.º 14
0
 void lookForLeafs(MonomialIterator w,MonomialIterator e) {
     TrieLocation L;
     Variable v;
     bool go = true;
     while(w!=e&&go) {
         v = *w;
         if(findRoot(L,v)) {
             ++w;
         } else {
             go = lookForLeafs(L,w,e);
         };
     };
 };
 int countComponents(int n, vector<pair<int, int>>& edges) {
     // start coding at 1:50
     // create nodes vec
     vector<int> roots;
     for (int i = 0; i < n; i++) roots.push_back(i);
     
     // traverse edges
     for (auto e : edges) {
         int i = findRoot(e.first, roots);
         int j = findRoot(e.second, roots);
         roots[j] = i;
     }
     
     // count roots
     int ans = 0;
     for (int i = 0; i < n; i++) {
         if (roots[i] == i) ans += 1;
     }
     
     // return
     return ans;
 }
 int countComponents(int n, vector<pair<int, int> >& edges) {
     root = vector<int>(n, -1);
     int size = edges.size();
     //int count = n;
     for(int i = 0; i < size; ++i)
     {
         int u = edges[i].first;
         int v = edges[i].second;
         int uroot = findRoot(u);
         int vroot = findRoot(v);
         if(uroot != vroot)
         {
             //--count;
             unionSet(uroot, u, vroot, v);
         }
     }
     int count = 0;
     for (int i = 0; i < n; i++) {
         if (findRoot(i) == i)
             count++;
     }
     //return count;
     return count;
 }
	TreeNode *buildBinaryTree(int beginIn, int beginPost, int len){
		if(len <= 0){
			return NULL;
		}
		TreeNode *root = new TreeNode(post[beginPost + len - 1]);
		int rootPos = findRoot(post[beginPost + len - 1], beginIn, len);
		if(rootPos == -1){
			return NULL;
		}
		int newLenLeft = rootPos;
		int newLenRight = len - newLenLeft - 1;
		root->left = buildBinaryTree(beginIn, beginPost, newLenLeft);
		root->right = buildBinaryTree(beginIn + rootPos + 1, beginPost + newLenLeft, newLenRight);
		return root;
	}
Ejemplo n.º 18
0
void UniformVector::associate() {
	
	Uniform::associate();
	
	// Doesn't have link
	if (!hasLink())
		return;
	
	// Find the link
	transformable = Scout<Transformable>::search(findRoot(this), getLink());
	if (transformable == NULL) {
		NodeException e(tag);
		e << "[UniformVector] Could not find node '" << getLink() << "'.";
		throw e;
	}
}
	TreeNode *buildBinaryTree(int beginIn, int beginPre, int len){
		if(len <= 0){
			return NULL;
		}
		int rootValue = pre[beginPre];
		TreeNode *root = new TreeNode(rootValue);
		int rootPos = findRoot(rootValue, beginIn, len);
		if(rootPos == -1){
			return NULL;
		}
		int newLenLeft = rootPos;
		int newLenRight = len - newLenLeft - 1;
		root->left = buildBinaryTree(beginIn, beginPre + 1, newLenLeft);
		root->right = buildBinaryTree(beginIn + newLenLeft + 1, beginPre + newLenLeft + 1, newLenRight);
		return root;
	}
Ejemplo n.º 20
0
Skeleton
Skeletonize::getSkeleton() {

	UTIL_TIME_METHOD;

	findBoundaryNodes();

	initializeEdgeMap();

	findRoot();

 	for (int i = 0; i < _parameters.maxNumSegments; ++i) {
 		if (!extractLongestSegment()) break;
	}
	return parseVolumeSkeleton();
}
  void unionWith(ptr_tag<CDA_ComputationTarget> b)
  {
    findRoot();
    b->findRoot();

    if (parent == b->parent)
      return;

    if (parent->rank > b->parent->rank)
      b->parent->parent = parent;
    else if (b->parent->rank > parent->rank)
      parent->parent = b->parent;
    else
    {
      b->parent->parent = parent;
      parent->rank++;
    }
  }
Ejemplo n.º 22
0
int DisjointSet::findRoot(const uint element) {
	int max, min;
	
	max = m_sets.size() - 1;
	min = 0;

	if ( (element > max) || (element < min) ) {
		return -1;
	}

	if (m_sets[element] < 0)
		return element;
	
	// Flattens the 'tree'
	m_sets[element] = findRoot(m_sets[element]);

	return m_sets[element];
}
Ejemplo n.º 23
0
void drawFunctions()
{
    const float STEP = graphWin.findSmartStepX();
    glPointSize(2.0f);

    //Draw selected  (f(x))
    for(float x=graphWin.xMin(); x<graphWin.xMax(); x+=STEP)
        graphWin.plot(x, f(x), 1.0f,0.5f,0.0f);

    //Draw f(x) = x
    for(float x=graphWin.xMin(); x<graphWin.xMax(); x+=STEP)
        graphWin.plot( x, x, 0.5f,0.5f,0.5f);

    //Draw g(x)
    for(float x=graphWin.xMin()+STEP; x<graphWin.xMax(); x+=STEP)
        graphWin.plot(x, g(x), 1.0f,0.5f,1.0f);

    clear();
    printHeader();
    std::cout << "x est compris dans l'ensemble [" << graphWin.xMin() << ";" << graphWin.xMax() << "[" << std::endl;
    std::cout << "y est compris dans l'ensemble [" << graphWin.yMin() << ";" << graphWin.yMax() << "[" << std::endl << std::endl;
    std::cout << "Information graphique : " << std::endl
              << "- Fonction choisie (f(x)) en orange" << std::endl
              << "- Fonction h(x) = x, en gris" << std::endl
              << "- Fonction g(x) = x + l*f(x), l = 1, en rose" << std::endl
              << "- Les axes x,y en bleu " << std::endl
              << "- Les vecteurs unitaires en rouge " << std::endl
              << "- Les solutions de la fonction en vert" << std::endl << std::endl;

    vector<long double> solutions = findRoot();
    std::cout << "Solutions : " << std::endl;

    glColor3f(0.0f, 1.0f, 0.0f);
    glPointSize(10);

    //Draw solutions
    for(unsigned int i = 0;i < solutions.size(); ++i)
    {
        std::cout << "[" << i << "] -> " << static_cast<double>(solutions[i]) << std::endl;
        glBegin( GL_POINTS );
            glVertex3d(solutions[i], 0, 0.0);
        glEnd();
    }
}
Ejemplo n.º 24
0
// Calculates the roots of tan(x*a)=-x/h
Real
GreensFunction1DRadAbs::root_n(int n) const
{
    const Real L( this->geta()-this->getsigma() );
    const Real h( (this->getk()+this->getv()/2.0) / this->getD() );
    // the drift v also comes into this constant, h=(k+v/2)/D
    Real upper, lower;

    if ( h*L < 1 )
    {
	// 1E-10 to make sure that he doesn't include the transition 
	lower = (n-1)*M_PI + 1E-10;
	// (asymptotic) from infinity to -infinity
	upper =  n   *M_PI - 1E-10;
    }
    else
    {
	lower = (n-1)*M_PI + M_PI_2 + 1E-10;
	upper = n    *M_PI + M_PI_2 - 1E-10;
    }

    gsl_function F;
    struct tan_f_params params = { L, h };
     
    F.function = &GreensFunction1DRadAbs::tan_f;
    F.params = &params;

    // define a new solver type brent
    const gsl_root_fsolver_type* solverType( gsl_root_fsolver_brent );

    // make a new solver instance
    // TODO: incl typecast?
    gsl_root_fsolver* solver( gsl_root_fsolver_alloc( solverType ) );
    // get the root = run the rootsolver
    const Real root( findRoot( F, solver, lower, upper, 1.0*EPSILON, EPSILON,
                            "GreensFunction1DRadAbs::root_tan" ) );
    gsl_root_fsolver_free( solver );
    
    return root/L;
    // This rescaling is important, because the function tan_f is used to solve for
    // tan(x)+x/h/L=0, whereas we actually need tan(x*L)+x/h=0, So if x solves the 
    // subsidiary equation, x/L solves the original one.
}
Ejemplo n.º 25
0
// This prints out the tree in Newick form.
void Tree::createNewickFile(string f) {
	try {
		int root = findRoot();
	
		filename = f;

		m->openOutputFile(filename, out);
		
		printBranch(root, out, "branch");
		
		// you are at the end of the tree
		out << ";" << endl;
		out.close();
	}
	catch(exception& e) {
		m->errorOut(e, "Tree", "createNewickFile");
		exit(1);
	}
}
Ejemplo n.º 26
0
 /**
  * Solves qubic equation ax^3 + bx^2 + cx + d = 0
  * @param roots roots found
  * @return number of roots (should be 1 or 3)
  */
 int solve(FT* roots)
 {
   double q = (mA < 0) ? -1 : 1; 
   mA *= q;
   mB *= q;
   mC *= q;
   mD *= q;
   FT D = mB * mB - 3. * mA * mC;
   FT T = BNBMAX((BNBABS(mB) + BNBABS(mC) + BNBABS(mD)) / BNBABS(mA), 1.);
   int nr;
   if(D <= 0.) {
       nr = 1;
       findRoot(-T, T, roots);
   } else if(D > 0.) {
     FT Q = sqrt(D);
     FT x1 = (-mB - Q) / (3. * mA);
     FT x2 = (-mB + Q) / (3. * mA);
     FT f1 = f(x1);
     FT f2 = f(x2);
     if(f1 < 0.) {
       nr = 1;
       findRoot(x2, T, roots);
     } else if(f1 == 0.) {
       roots[0] = x1;
       if(f2 == 0.) {
         nr = 1;
       } else {
         nr = 2;
         findRoot(x2, T, roots + 1);
       }
     } else if(f1 > 0.) {
       findRoot(-T, x1, roots);
       if(f2 > 0.) {
         nr = 1;
       } else if(f2 == 0.) {
         nr = 2;
         roots[1] = x2;
       } else if(f2 < 0.) {
         nr = 3;
         findRoot(x1, x2, roots + 1);
         findRoot(x2, T, roots + 2);
       }
     }
   }
   mA *= q;
   mB *= q;
   mC *= q;
   mD *= q;
   return nr;
 }
Ejemplo n.º 27
0
//根据数组list,生成近似最有查找树T
void createSOSTree(BiTNode **T, node* list, int start, int end)
{
    /*
    伪代码:
    使用递归
    结束条件:start>end
    root=findRoot(list,start,end)
    *T=malloc();
    T->value=list[root];
    T->number=root;
    createSOSTree(T->lchild,list,start,root-1);
    createSOSTree(T->rchild,list,root+1,end);
    */

    if(start>end) return;
    int root    =   findRoot(list,start,end);
    *T          =   (BiTNode*) malloc(sizeof(BiTNode));
    (*T)->value =   list[root];
    (*T)->number=   root;
    createSOSTree(&((*T)->lchild),list,start,root-1);
    createSOSTree(&((*T)->rchild),list,root+1,end);
}
Ejemplo n.º 28
0
/*!
** @brief Lookup a DAG in the hosts.xia file
**
** @param name The name of an XIA service or host.
**
** @returns a character point to the dag on success
** @returns NULL on failure
**
*/
char *hostsLookup(const char *name) {
	char line[512];
	char *linend;
	char *dag;
	char _dag[NS_MAX_DAG_LENGTH];

	// look for an hosts_xia file locally
	FILE *hostsfp = fopen(strcat(findRoot(), ETC_HOSTS), "r");
	int answer_found = 0;
	if (hostsfp != NULL) {
		while (fgets(line, 511, hostsfp) != NULL) {
			linend = line+strlen(line)-1;
			while (*linend == '\r' || *linend == '\n' || *linend == '\0') {
				linend--;
			}
			*(linend+1) = '\0';
			if (line[0] == '#') {
				continue;
			} else if (!strncmp(line, name, strlen(name))
						&& line[strlen(name)] == ' ') {
				strncpy(_dag, line+strlen(name)+1, strlen(line)-strlen(name)-1);
				_dag[strlen(line)-strlen(name)-1] = '\0';
				answer_found = 1;
			}
		}
		fclose(hostsfp);
		if (answer_found) {
			dag = (char*)malloc(sizeof(_dag) + 1);
			strcpy(dag, _dag);
			return dag;
		}
	} else {
		//printf("XIAResolver file error\n");
	}

	//printf("Name not found in ./hosts_xia\n");
	return NULL;
}
Ejemplo n.º 29
0
// Calculates the roots of tan(aL)=-ak/h
const Real FirstPassageGreensFunction1DRad::a_n(const int n) const
{
    // L=length of domain=2*a
    const Real L(this->getL());
    // h=k/D
    const Real h(this->getk()/this->getD());
    Real upper, lower;

    if ( h*L < 1 )
    {
        // 1E-10 to make sure that he doesn't include the transition
        lower = (n-1)*M_PI + 1E-10;
        // (asymptotic) from infinity to -infinity
        upper =  n   *M_PI - 1E-10;
    }
    else
    {
        lower = (n-1)*M_PI + M_PI_2 + 1E-10;
        upper = n    *M_PI + M_PI_2 - 1E-10;
    }

    gsl_function F;
    struct tan_f_params params = { L, h};

    F.function = &FirstPassageGreensFunction1DRad::tan_f;
    F.params = &params;

    // define a new solver type brent
    const gsl_root_fsolver_type* solverType( gsl_root_fsolver_brent );

    // make a new solver instance
    // incl typecast?
    gsl_root_fsolver* solver( gsl_root_fsolver_alloc( solverType ) );
    const Real a( findRoot( F, solver, lower, upper, 1.0*EPSILON, EPSILON,
                            "FirstPassageGreensFunction1DRad::root_tan" ) );
    gsl_root_fsolver_free( solver );
    return a;
}
Ejemplo n.º 30
0
bool ChrsGrid::isDeadMap()
{
	//遍历每一个汉字元素
	for (int x = 0; x < m_col; x++)
	{
		//遍历列
		for (int y = 0; y < m_row; y++)
		{
			//存放可消除的汉字元素序列,用于系统提示
			m_AnswerChrs.clear();

			//从汉字元素盒子中选定一个汉字元素
			auto chr = m_ChrsBox[x][y];
			if (findRoot(chr))
			{
				return false;//找到路了,则不是死图,否则继续下一个chr
			}
		}
	}

	log ("this is a deadmap!");
	return true;
}