//
// minimum spanning tree, Kruskal
// start from the smallest weight edge, and join vertices in a tree, 
// as long as there is no cycle (ie both terminals in the same tree)
// to achieve that we need a set indicating each subtree, and merge
// the two corresponding sets when extracting an edge that joins two vertices.
// the union find mechanism works well and performs almost constant
float MST(const graphtp & g, pqtp & pq)
{
    vi uf(g.size()); //union find structure
    int visited = 0;
    float totpath = 0.0;

    //for each vertex need a set
    for(int n = 0; n < g.size(); n++)
        uf[n] = n;

    pqtp::iterator it = pq.begin();
    while(it != pq.end() && visited < g.size()) {
        edge e = *it; //extract min
        pq.erase(it++);

        //unionfind will return false if they are in the same tree
        if(false == unionfind(uf,e.to,e.from)) 
            continue;
        
        //process this edge
        printf ("%d - %d (%f)\n", e.from, e.to, e.weight);
        totpath += e.weight;
        visited++;
    }
    return totpath;
}
Exemple #2
0
int main(void){
	int m, n;
	for(RI(n), RI(m); (m || n); RI(n), RI(m)){
		int a, ans = 0, b, maxppa = MINPPA, ppa;
		FOR(i, n) cnt[i] = 0, p[i] = i;
		FOR(i, n) FORI(j, i + 1, n) adj[i][j] = MINPPA;
		FOR(i, m){
			RI(a), RI(b), RI(ppa);
			--a; --b;
			if(a > b) swap(a, b);
			if(ppa > adj[a][b]){
				adj[a][b] = ppa;
				maxppa = max(maxppa, ppa);				
			}
		}
		FOR(i, n) FORI(j, i + 1, n) if(adj[i][j] == maxppa) unionfind(i, j);
		FOR(i, n) ans = max(ans, ++cnt[findroot(i)]);
		printf("%d\n", ans);
	}
Exemple #3
0
int main(void) {
	memset(dad,sizeof(dad),0);


	/* lets union some prime numbers */
	unionfind(2,7,1);
	unionfind(3,11,1);
	unionfind(13,7,1);
	unionfind(5,7,1);
	unionfind(2,11,1);
	/* and some non prime */
	unionfind(8,1,1);
	unionfind(6,20,1);
	unionfind(1,6,1);

	printf("%d %d, %d\n", 2,7,unionfind(2,7,0));
	printf("%d %d, %d\n", 5,11,unionfind(5,11,0));
	printf("%d %d, %d\n", 5,8,unionfind(5,8,0));
	printf("%d %d, %d\n", 20,1,unionfind(20,1,0));
	
	return 0;
}