URAL 1303 Minimal Coverage (贪心)

#include <stdio.h>
#include <stdlib.h>

#define MAX_SEGMENTS 100000
typedef struct Segment{
	int left;
	int right;
}Segment;
Segment SegmentArray[MAX_SEGMENTS];
int numOfSegments;
int stack[MAX_SEGMENTS];
int top;

int cmp(const void *a, const void *b){
	return ((Segment *)a)-> left -  ((Segment *)b)->left;
}

int main(){
	
	int rightToCover;
	scanf("%d", &rightToCover);
	int left, right;
	while (scanf("%d%d", &left, &right) != EOF){
		if (left == 0 && right == 0)
			break;
		numOfSegments++;
		SegmentArray[numOfSegments].left = left;
		SegmentArray[numOfSegments].right = right;
	}

	qsort(&SegmentArray[1], numOfSegments, sizeof(SegmentArray[0]), cmp);

	int numOfSegmentsChosen = 0;
	int leftToCover = 0;
	int segment = 1;
	//贪心:从左往右覆盖,每次选取片段的策略是在保证能覆盖到等待覆盖的左端点的前提下,尽可能地往右边覆盖,在选定一个片段并进行覆盖之后更新等待覆盖的左端点
	while (segment <= numOfSegments){
		int maxRight = -1;
		int segmentChosen = 0;
		while (segment <= numOfSegments && SegmentArray[segment].left <= leftToCover){
			if (SegmentArray[segment].right > maxRight){
				maxRight = SegmentArray[segment].right;
				segmentChosen = segment;
			}
			segment++;
		}
		if (maxRight == -1)
			break;
		numOfSegmentsChosen++;
		stack[numOfSegmentsChosen] = segmentChosen;
		leftToCover = maxRight;
		if (leftToCover >= rightToCover)
			break;
	}

	if (leftToCover < rightToCover)
		printf("No solution\n");
	else {
		printf("%d\n", numOfSegmentsChosen);
		int top;
		for (top = 1; top <= numOfSegmentsChosen; top++){
			segment = stack[top];
			printf("%d %d\n", SegmentArray[segment].left, SegmentArray[segment].right);
		}
	}

	return 0;
}


 

你可能感兴趣的:(coverage,minimal,贪心,ural,1303)