예제 #1
0
bool Connect()
{
    int i, prev=-1, setNums=1;
    for (i=0; i<26; ++i)
        parent[i] = i;
    
    for (i=0; i<N; ++i)
    {
        if ( edge[i].u!=edge[i].v && FindSet(edge[i].u)!=FindSet(edge[i].v) )
            Merge(edge[i].u, edge[i].v);
    }
        
    for (i=0; i<26; ++i)
    {
        if ( !hash[i] ) continue;
        if ( prev==-1 ) prev = i;
        else if ( parent[i]!=parent[prev] )
            break;
    }// counting set's number
    
    //return true;
    if ( i<26 ) return false;
    else    return true;
    //return ( setNums==1 ? true:false );
}// Connect
예제 #2
0
void DisjointSet::UnionSet(int x, int y)
{
  if (x < 0 || x >= size)
  {
    printf("Error in DisjointSet::UnionSet(int x, int y): the x value is illegal.\n");
    exit(0);
  }
  if (y < 0 || y >= size)
  {
    printf("Error in DisjointSet::UnionSet(int x, int y): the y value is illegal.\n");
    exit(0);
  }
  int ancestor1 = FindSet(x);
  int ancestor2 = FindSet(y);
  if (ancestor1 == ancestor2)
    return; // they are already in the same set

  if (disjointSetParent[ancestor1] < disjointSetParent[ancestor2]) // size of set 1 is larger
  {
    disjointSetParent[ancestor1] += disjointSetParent[ancestor2];
    disjointSetParent[ancestor2] = ancestor1;
  }
  else  // size of set 2 is larger or equal to the size of set 1
  {
    disjointSetParent[ancestor2] += disjointSetParent[ancestor1];
    disjointSetParent[ancestor1] = ancestor2;
  }
}
예제 #3
0
int main()
{
  int t1,t2;
  int ilosc;
  int wyb=0;
  printf("\nZbiory rozlaczne\n");
  printf("1 - wstaw\n");
  printf("2 - polacz\n");
  printf("3 - drukuj\n");
  printf("4 - sprawdz\n");
  printf("5 - koniec\n");
  
  
  while(wyb!=5){
    printf("\nWybor: "); 
    scanf("%d",&wyb);
  switch(wyb)
    {
    case 1:  
      printf("Jednoelementowe zbiory\n");
      printf("Ile ma ich byc?\n");
      scanf("%d",&ilosc);
      createSets(ilosc);
      printSets(ilosc);
      break;
    case 2:
      printf("\nktore zbiory chcesz polaczyc\n");
      scanf("%d",&t1);
      scanf("%d",&t2);
      if(t1 > ilosc){
	return 0;
      }
      if(t2 > ilosc){
	return 0;
      }
      break;
    case 3:
      printSets(ilosc);
      break;
    case 4:
      /* printf("\n%d ",FindSet(Z[t1]));*/
      /* printf("%d ",FindSet(Z[t2]));*/
      Union(FindSet(Z[t1]), FindSet(Z[t2]));
      /* printf("\n%d ",FindSet(Z[t1]));*/
      /* printf("%d ",FindSet(Z[t2]));*/
      printSets(ilosc);
      break;
    case 5:
      return 0;
      break;
    }
  }
      return 0;
}
void Merge( int xx, int yy )
{
    int r1 = FindSet( xx );
    int r2 = FindSet( yy );
    if ( r1==r2 )
        return ;
    
    if ( r1<r2 )
        parent[r2] = r1;
    else
        parent[r1] = r2;
}// Merge
예제 #5
0
bool Merge(int x, int y)
{
    int r1 = FindSet( x );
    int r2 = FindSet( y );
    if ( r1==r2 )
        return false;
    
    if ( r1<r2 )
        hub[r2] = r1;
    else
        hub[r1] = r2;
    
    return true;
}// Merge
예제 #6
0
inline DisjointSets2::CompIndex DisjointSets2::Union(
    const DisjointSets2::CompIndex & set_x,
    const DisjointSets2::CompIndex & set_y) {
    maggieDebug3("Union(%i, %i)", set_x, set_y);

    CompIndex root_x = FindSet(set_x);
    CompIndex root_y = FindSet(set_y);
    if (root_x == root_y)
        return root_x;

    --nb_comp;

    // The first way, called union by rank, is to always attach
    // the smaller tree to the root of the larger tree, rather than vice versa.
    // Since it is the depth of the tree that affects the running time,
    // the tree with smaller depth gets added under the root of the deeper tree,
    // which only increases the depth if the depths were equal.
    // In the context of this algorithm, the term rank is used instead of depth
    // since it stops being equal to the depth if path compression
    // (described below) is also used.
    // One-element trees are defined to have a rank of zero,
    // and whenever two trees of the same rank r are united,
    // the rank of the result is r+1.
    // Just applying this technique alone yields an amortized running-time
    // of O(logn) per MakeSet, Union, or Find operation.
    if (ranks[root_x] < ranks[root_y]) {
        roots[root_x] = root_y;

        // update biggest_comp_idx
        if ( (sizes[root_y] += sizes[root_x]) > biggest_comp_size) {
            biggest_comp_idx = root_y;
            biggest_comp_size = sizes[root_y];
        }
        return root_y;
    }
    else {//if (ranks[root_x] >= ranks[root_y]) {
        roots[root_y] = root_x;

        // update biggest_comp_idx
        if ( (sizes[root_x] += sizes[root_y]) > biggest_comp_size) {
            biggest_comp_idx = root_x;
            biggest_comp_size = sizes[root_x];
        }

        if (ranks[root_x] == ranks[root_y])
            ++ranks[root_x];
        return root_x;
    }
}
예제 #7
0
파일: kruskal.c 프로젝트: alior/nwp
krawedz *kruskal(krawedz *x, int lk, int lw){
	int i;
	wezel *W[lw+1];
	for(i=1;i<=lw;i++){
		W[i]=MakeSet(i);
	}
	for(i=0;i<lk;i++){
		if(FindSet(W[x[i].w1]) != FindSet(W[x[i].w2]) ){
			/*printf("\n%d.) KRAWEDZ %d-%d o wadze %d \n", i+1, x[i].w1, x[i].w2, x[i].waga);
			printf("    ");
			for(j=1;j<=lw;j++){
				printf("%d ", FindSet(W[j])->head->key);
			}
			printf(" w1:");
			pom=FindSet(W[x[i].w1]);
			for(j=1;pom!=NIL;j++){
				printf("%d->",pom->key);
				pom=pom->next;
			}
			printf(" w2:");
			pom=FindSet(W[x[i].w2]);
			for(j=1;pom!=NIL;j++){
				printf("%d->",pom->key);
				pom=pom->next;
			}
			printf("\n");*/
			x[i].roz=1;
			Union(FindSet((W[x[i].w1])), FindSet((W[x[i].w2])));
			/*printf("    ");
			for(j=1;j<=lw;j++){
				printf("%d ", FindSet(W[j])->head->key);
			}
			printf(" w1:");
			pom=FindSet(W[x[i].w1]);
			for(j=1;pom!=NIL;j++){
				printf("%d->",pom->key);
				pom=pom->next;
			}
			printf(" w2:");
			pom=FindSet(W[x[i].w2]);
			for(j=1;pom!=NIL;j++){
				printf("%d->",pom->key);
				pom=pom->next;
			}
			printf("\n");*/
		}
	}
	return x;
}
예제 #8
0
void Merge(int x, int y)
{
    int r1 = FindSet(x);
    int r2 = FindSet(y);
    
    if (r1 == r2)
        return ;
    
    if (r1 > r2)
        edge[r1] = r2; 
    else
        edge[r2] = r1;
        
    return ;
}/* Merge */
예제 #9
0
t_node* FindSet(t_node* x)
{
  /* zwraca reprezentanta zbioru do ktorego nalezy element (czyli wezel) x*/
  /* Wersja bez kompresji*/
  if (x != x -> p) { return FindSet(x->p);}
  else {return x;}
}
예제 #10
0
/*!
    \fn DisJointSet::Consolidate()
 */
std::vector<std::vector<int> > DisJointSet::Consolidate()
{
        int k = 0,dest;
        std::vector<std::vector<int> > ConsolidatedSet;
        std::map<int, int> Map;

        for (unsigned int i = 0; i < nodes.size(); i++)
        {
                if (nodes[i].Parent == 0)
                {
                        Map.insert(std::pair<int,int>(nodes[i].Index,k));
                        std::vector <int> temp;
                        ConsolidatedSet.push_back(temp);
                        ConsolidatedSet[k].push_back(nodes[i].ElementIndex);
                        k++;
                }
        }
        for (unsigned int i = 0; i < nodes.size(); i++)
        {
                if (nodes[i].Parent != 0)
                {
                        dest = Map[nodes[FindSet(i)].Index];
                        ConsolidatedSet[dest].push_back(nodes[i].ElementIndex);
                }
        }
        return(ConsolidatedSet);
}
예제 #11
0
파일: mintree.c 프로젝트: Avi2011class/Test
void UnionSets(struct DSU* D, int X, int Y)
{
    X = FindSet(D, X);
	Y = FindSet(D, Y);
	if (X != Y)
    {
        if (D->Range[X] < D->Range[Y])
        {
            int Buf = X;
            X = Y;
            Y = Buf;
        }
		D->Parent[Y] = X;
		D->Range[X] += D->Range[Y];
    }
}
예제 #12
0
size_t
DisjointSet::FindSet(size_t x)
{
	if (x != p[x])
		p[x] = FindSet(p[x]);

	return p[x];
}
예제 #13
0
//unions the sets to which i and j belong
int UnionFind::Union(const int i,const int j)
{
	int root_i=FindSet(i),root_j=FindRoot(j);
	PathCompress(j,root_i);
	if(root_i!=root_j)
		parents[root_j]=root_i;
	return root_i;
}
예제 #14
0
파일: HDOJ1213.c 프로젝트: OlafLee/ACM-ICPC
int FindSet(int k)
{
    if (k != parent[k])
    {
        k = FindSet(parent[k]);
    }/* End of If */
    
    return k;
}
UNode<TYPE>* DisjointSets< TYPE, _Compare >::getRepresentativeNode(const TYPE& elementArg) const
{
	// -> we have to use .at(), because [] creates the object if it is not found! we do not want that
	m_elementForComparison = &elementArg;
	UNode<TYPE>* assocNode = m_storedPointers.at(m_lookupConstant);
	m_elementForComparison = NULL;
	UNode<TYPE>* representativeNode = FindSet(assocNode);
	return representativeNode;
}
Parent *FindSet(Parent *find)
  {
  if (find->par != NULL)
    {
    find->par = FindSet(find->par);
    return find->par;
    }
  return find;
  }
예제 #17
0
    // Return the current set of roots (or representatives) for 
    // each of the partition
    std::set<int> GetRoots() const
    {
      std::set<int> roots;
      for (elements_t::const_iterator it=elements_.begin(); it!=elements_.end(); ++it) {
	if (FindSet(*it) == *it) {
	  roots.insert(*it);
	}
      }
      return roots;
    }
예제 #18
0
파일: mintree.c 프로젝트: Avi2011class/Test
int FindSet(struct DSU* D, int V)
{
    if(D->Parent[V] == V)
        return V;
    else
    {
        D->Parent[V] = FindSet(D, D->Parent[V]);
        return D->Parent[V];
    }

}
예제 #19
0
void IPCSetEvent(int argc, char** argv, PLSOBJECT Object)
{
	char* Name = argv[0];
	char* Method = argv[1];

	LSOBJECT setobject;
	if((setobject.Ptr = FindSet(Name)) == 0)
	{
		setobject.Ptr = new LSSet();
		AddSet(Name, (LSSet*)setobject.Ptr);
	}
	pSetType->GetMethodEx(setobject.GetObjectData(), Method, argc - 2, &argv[2]);
}
예제 #20
0
// Begin enumeration for tests in a specific BIT sets
bool CBITManager::BeginTestsInSetEnumeration(QString SetName)
{
  int SetID = FindSet(SetName);

  // Return false is the requested BIT set could not be found
  if(SetID != -1)
  {
    m_CurrentSet = SetID;
    m_CurrentTestInSet = 0;
    return true;    
  }

  return false;
}
예제 #21
0
int main()
{
  int t1,t2;
  int ilosc,k=0;
  while(k!=4){
    printf("\nDodaj - 1\nDrukuj - 2\nPolacz - 3\nWyjdz - 4\n");
    scanf("%d",&k);
  switch(k)
{
  case 1:
         printf("Jednoelementowe zbiory\n");
         printf("Ile ma ich byc\n");
         scanf("%d",&ilosc);
         createSets(ilosc);
         break;
  case 2:
         printSets(ilosc);
    break;
  case 3:
      printf("\nktore zbiory chcesz polaczyc\n");
         scanf("%d",&t1);
         scanf("%d",&t2);
         if(t1 > ilosc){
           return 0;
         }
         if(t2 > ilosc){
           return 0;
         }
         Union(FindSet(Z[t1]), FindSet(Z[t2]));
    break;
 case 4:
      return 0;
    break;
  }
  }
         return 0;
}
예제 #22
0
파일: HDOJ1213.c 프로젝트: OlafLee/ACM-ICPC
void Union(int x, int y)
{
    /* 查找x,y所从属的集合 */ 
    x = FindSet(x);
    y = FindSet(y);
    if (x == y)
    {
        return ;
    }
    
    /* 路径压缩 */ 
    if (rank[x] > rank[y])
    {
        parent[y] = x;
    }
    else
    {
        if (rank[x] == rank[y])
        {
            ++rank[y];
        }
        parent[x] = y;
    }/* End of Else */
}
예제 #23
0
파일: mintree.c 프로젝트: Avi2011class/Test
int main(void)
{
    int N, M, i;
    scanf("%d %d", &N, &M);
    struct edge* E = (struct edge*)malloc(sizeof(struct edge) * M);
    for(i = 0; i < M; i++)
        scanf("%d %d %d", &(E[i].first), &(E[i].second), &(E[i].length));
    qsort(E, M, sizeof(struct edge), cmp_edge);

    struct DSU* D = Init(N);
    for(i = 0; i < N; i++)
        MakeNewSet(D, i);
    int res = 0;
    for(i = 0; i < M; i++)
    {
        if(FindSet(D, E[i].first) != FindSet(D, E[i].second))
        {
            res += E[i].length;
            UnionSets(D, E[i].first, E[i].second);
        }
    }
    printf("%d", res);
    return 0;
}
예제 #24
0
    // Stringify the data-structure
    std::string ToString() const
    {
      std::stringstream ss;
      std::set<int> roots = GetRoots();
      ss << "{ ";
      for (std::set<int>::const_iterator rit = roots.begin(); 
	                                 rit != roots.end(); ++rit) {
	ss << "[ " << *rit ;
	for (elements_t::const_iterator eit=elements_.begin(); eit!=elements_.end();++eit) {
	  if (*eit != *rit && FindSet(*eit) == *rit) {
	    ss << ", " << *eit;
	  }
	}
	ss << " ] ";
      }
      ss << "}";
      return ss.str();
    }
예제 #25
0
cv::Point DisjointSets2::centroidOfMonochromeImage(const int cols) {
    // iterate on the roots to collect the answers
    CompIndex* roots_ptr = roots;
    double x_tot = 0, y_tot = 0;

    for(CompIndex row = 0 ; row < count / cols ; ++row) {
        for(CompIndex col = 0 ; col < cols ; ++col) {
            if ( *roots_ptr != NO_NODE
                    && FindSet(*roots_ptr) == biggest_comp_idx ) {
                x_tot += col;
                y_tot += row;
            }
            ++roots_ptr;
        } // end loop row
    } // end loop col

    return cv::Point(x_tot / biggest_comp_size, y_tot / biggest_comp_size);
}
예제 #26
0
void EditPatchMod::ActivateSubSelSet(TSTR &setName)
{
	MaybeFixupNamedSels();
	ModContextList mcList;
	INodeTab nodes;
	int index = FindSet(setName, selLevel);
	if (index < 0 || !ip)
		return;	
	
	ip->GetModContexts(mcList, nodes);
	
	theHold.Begin();
	for (int i = 0; i < mcList.Count(); i++)
	{
		EditPatchData *patchData =(EditPatchData*)mcList[i]->localData;
		if (!patchData)
			continue;		
		RPatchMesh *rpatch;
		PatchMesh *patch = patchData->TempData(this)->GetPatch(ip->GetTime(), rpatch);
		if (!patch)
			continue;
		patchData->BeginEdit(ip->GetTime());
		// If that set exists in this context, deal with it
		GenericNamedSelSetList &sel = patchData->GetSelSet(this);
		BitArray *set = sel.GetSet(setName);
		if (set)
		{
			if (theHold.Holding())
				theHold.Put(new PatchSelRestore(patchData, this, patch));
			BitArray *psel = GetLevelSelectionSet(patch, rpatch);	// Get the appropriate selection set
			AssignSetMatchSize(*psel, *set);				
			PatchSelChanged();
		}
		
		patchData->UpdateChanges(patch, rpatch, FALSE);
		if (patchData->tempData)
			patchData->TempData(this)->Invalidate(PART_SELECT);
	}
	
	theHold.Accept(GetString(IDS_DS_SELECT));
	nodes.DisposeTemporary();	
	NotifyDependents(FOREVER, PART_SELECT, REFMSG_CHANGE);
	ip->RedrawViews(ip->GetTime());
}
예제 #27
0
파일: UVa-10583.cpp 프로젝트: Cayonliow/acm
int main()
{
    int n,m,i,j,h,a,b,mark;
    h=0;
    while(scanf("%d %d",&n,&m)==2)
    {
    	mark=0;
        if(n==0&&m==0)
            return 0;
        
        
        for(i=1;i<=n;i++)
        {
           MakeSet(i);
        }
		 
		 for(i=0;i<m;i++)
		 {
		 	scanf("%d %d",&a,&b);
		 	Union(a,b);
		 }
		 
        for(i=1;i<=n;i++)
        {
            record[FindSet(i)]++;
        }
    
        for(i=1;i<=n;i++)
        {
            if(record[i]!=0)
            {
                mark++;
            }
       
        }
        h++;
    printf("Case %d: %d\n",h,mark);
	mark=0;
    }
 return 0;
}
예제 #28
0
void DisjointSets2::biggestComponent_image(const int cols, cv::Mat1b & imgRep) {
    imgRep = 0;

    // if biggest comp is empty, do not iterate !
    if (biggest_comp_size == 0)
        return;

    // iterate on the roots to collect the answers
    CompIndex* roots_ptr = roots;
    for(CompIndex row = 0 ; row < count / cols ; ++row) {
        // get the address of row
        uchar* data = imgRep.ptr<uchar>(row);
        for(CompIndex col = 0 ; col < cols ; ++col) {
            if ( *roots_ptr != NO_NODE
                    && FindSet(*roots_ptr) == biggest_comp_idx )
                *data = 255;
            ++data;
            ++roots_ptr;
        } // end loop col
    } // end loop row
}
예제 #29
0
inline DisjointSets2::CompIndex DisjointSets2::FindSet(
    const DisjointSets2::CompIndex & element) {
    maggieDebug3("FindSet(%i)", element);

    if (roots[element] == element)
        return element;
    else {
        // The second improvement, called path compression, is a way of
        // flattening the structure of the tree whenever Find is used on it.
        // The idea is that each node visited on the way to a root node may
        // as well be attached directly to the root node;
        // they all share the same representative.
        // To effect this, as Find recursively traverses up the tree,
        // it changes each node's parent reference to point to the root that it found.
        // The resulting tree is much flatter, speeding up future operations
        // not only on these elements but on those referencing them,
        // directly or indirectly.
        roots[element] = FindSet( roots[element] );
        return roots[element];
    }
}
예제 #30
0
void DisjointSets2::biggestComponent_vector(const int cols,
        Comp & rep) {
    rep.clear();

    // if biggest comp is empty, do not iterate !
    if (biggest_comp_size == 0)
        return;

    // iterate on the roots to collect the answers
    CompIndex* roots_ptr = roots;
    rep.reserve( biggest_comp_size );

    for(CompIndex y = 0 ; y < count / cols ; ++y) {
        for(CompIndex x = 0 ; x < cols ; ++x) {
            if ( *roots_ptr != NO_NODE
                    && FindSet(*roots_ptr) == biggest_comp_idx )
                rep.push_back( cv::Point(x, y) );

            ++roots_ptr;
        } // end loop x
    } // end loop y
}