POJ 3687 Labeling Balls (反向拓扑排序)

#include <stdio.h>
#define MAX_LABEL 200
#define MAX_WEIGHT 200
#define MAX_CONSTAINS 40000

int numOfBalls, numOfConstrains;
int maxLabel, maxWeight;
int lighter, heavier;
int fail;
int label, weight;
int weightOfBall;
int hasConstrain[MAX_LABEL + 1][MAX_LABEL + 1];
int inDegree[MAX_LABEL + 1];
int visited[MAX_LABEL + 1];
int labelOfBall[MAX_WEIGHT + 1];

int main(){

	int testCases;
	scanf("%d", &testCases);
	while (testCases--){
		scanf("%d%d", &numOfBalls, &numOfConstrains);

		maxLabel = numOfBalls;
		maxWeight = numOfBalls;

		for (lighter = 1; lighter <= maxLabel; lighter++){
			visited[lighter] = 0;
			inDegree[lighter] = 0;
			for (heavier = 1; heavier <= maxLabel; heavier++)
				hasConstrain[lighter][heavier] = 0;
		}

		int i;
		for (i = 1; i <= numOfConstrains; i++){
			scanf("%d%d", &lighter, &heavier);
			if (hasConstrain[lighter][heavier] == 0){
				hasConstrain[lighter][heavier] = 1;
				inDegree[lighter]++;
			}
		}

		fail = 0;
		for (label = maxLabel; label > 0; label--){
			weightOfBall = 0;
			for (weight = maxWeight; weight > 0; weight--)
				if (visited[weight] == 0 && inDegree[weight] == 0){
					weightOfBall = weight;
					break;
				}

			if (weightOfBall == 0){
				fail = 1;
				break;
			}
			visited[weightOfBall] = 1;
			labelOfBall[weightOfBall] = label;

			for (lighter = 1; lighter <= maxLabel; lighter++)
				if (hasConstrain[lighter][weightOfBall])
					inDegree[lighter]--;
		}

		if (fail)
			printf("-1\n");
	    else {
			for (weight = 1; weight <= maxWeight; weight++)
				printf("%d ", labelOfBall[weight]);
			printf("\n");
		}
	}

	return 0;
}

你可能感兴趣的:(poj,labeling,3687,反向拓扑排序,Balls)