POJ 1251 Jungle Roads (最小生成树 Kruskal克鲁斯卡尔算法)

#include <stdio.h>

#define MAX_ROADS 76
#define MAX_VILLAGES 27

struct ROAD{
	int start;
	int end;
	int cost;
};

ROAD roadArray[MAX_ROADS];
int numOfRoads;
int roadNum;

int numOfVillages;

int parent[MAX_VILLAGES];

void roadCopy(ROAD *to, ROAD *from){
	ROAD temproad;
	temproad.start = from->start;
	temproad.end = from->end;
	temproad.cost = from->cost;
	from->start = to->start;
	from->end = to->end;
	from->cost = to->cost;
	to->start = temproad.start;
	to->end = temproad.end;
	to->cost = temproad.cost;
}
void quickSortroadsAccordingToCost(int start, int end){
	if (start >= end){
		return;
	}
	while (start < end){
		int left = start;
		int right = end;
		ROAD pivotroad;
		roadCopy(&pivotroad, &roadArray[start]);
		while (left < right){
			while (left < right && roadArray[right].cost >= pivotroad.cost){
				right--;
			}
			roadCopy(&roadArray[left], &roadArray[right]);
			while (left < right && roadArray[left].cost <= pivotroad.cost){
				left++;
			}
			roadCopy(&roadArray[right], &roadArray[left]);			
		}
		roadCopy(&roadArray[left], &pivotroad);
		int pivot = left;
		quickSortroadsAccordingToCost(start, pivot - 1);
		start = pivot + 1;
	}
}

int getParent(int villageNum){
	while (parent[villageNum]){
		villageNum = parent[villageNum];
	}
	return villageNum;
}
int main(){
	//freopen("input.txt", "r", stdin);

	while (1){
		scanf("%d", &numOfVillages);
		if (numOfVillages == 0){
			return 0;
		}

		numOfRoads = 0;
		int indexOfVillage;
		for (indexOfVillage = 1; indexOfVillage <= numOfVillages; indexOfVillage++){
			parent[indexOfVillage] = 0;
		}

		for (indexOfVillage = 1; indexOfVillage < numOfVillages; indexOfVillage++){
			char villageLetter;
			int numOfAdjaRoads;
			scanf(" %c %d", &villageLetter, &numOfAdjaRoads);
			int start = villageLetter - 'A' + 1;
			int indexOfRoad;
			for (indexOfRoad = 1; indexOfRoad <= numOfAdjaRoads; indexOfRoad++){
				int cost;
				scanf(" %c %d", &villageLetter, &cost);
				int end = villageLetter - 'A' + 1;
				numOfRoads++;
				roadNum = numOfRoads;
				roadArray[roadNum].start = start;
				roadArray[roadNum].end = end;
				roadArray[roadNum].cost = cost;
			}
		}

		quickSortroadsAccordingToCost(1, numOfRoads);

		int minTotalCost = 0;
		int indexOfRoad;
		for (indexOfRoad = 1; indexOfRoad <= numOfRoads; indexOfRoad++){
			int start = roadArray[indexOfRoad].start;
			int end = roadArray[indexOfRoad].end;
			int parentOfStart = getParent(start);
			int parentOfEnd = getParent(end);
			if ( parentOfStart != parentOfEnd ){
				parent[parentOfStart] = parentOfEnd;
				minTotalCost += roadArray[indexOfRoad].cost;
			}
		}

		printf("%d\n", minTotalCost);		
	}
}

你可能感兴趣的:(最小生成树,poj,克鲁斯卡尔,1251,Jungle,Roads)