POJ 3614 Sun Bathing (贪心)

来源:互联网 发布:视频放大的软件 编辑:程序博客网 时间:2024/06/17 22:09
#include<stdio.h>#include<malloc.h>#define MAX 2501int cows;int bottles;int minSPF[MAX];int maxSPF[MAX];int lotionSPF[MAX];int covers[MAX];struct node{int SPF;node *pNext;};node *head = NULL;//head of ordered list/* consider 3 locations to insert */void insert(int SPF){node *pNew = (node *)malloc(sizeof(node));pNew->SPF = SPF;pNew->pNext = NULL;if (head == NULL){head = pNew;return;}// insert to headif (SPF <= head->SPF){pNew->pNext = head;head = pNew;return;}node *pBefore = head;node *pAfter = head;while (pAfter != NULL  && pAfter->SPF <= SPF){pBefore = pAfter;pAfter= pAfter->pNext;}//insert to tailif (pAfter == NULL){pBefore->pNext = pNew;return;}//insert to middlepNew->pNext = pAfter;pBefore->pNext = pNew;}void quickSortBottles(int first, int last){if (first >= last){return;}while (first < last){int left = first;int right = last;int pivotValue = lotionSPF[left];int tempOfCover = covers[left];while (left < right){while (left < right && lotionSPF[right] >= pivotValue){right--;}lotionSPF[left] = lotionSPF[right];covers[left] = covers[right];while (left < right && lotionSPF[left] < pivotValue){left++;}lotionSPF[right] = lotionSPF[left];covers[right] = covers[left];}lotionSPF[left] = pivotValue;covers[left] = tempOfCover;int pivot = left;quickSortBottles(first, pivot - 1);first = pivot + 1;}}void quickSortCows(int first, int last){if (first >= last){return;}while (first < last){int left = first;int right = last;int pivotValue = minSPF[left];int tempOfMaxSPF = maxSPF[left];while (left < right){while (left < right && minSPF[right] >= pivotValue){right--;}minSPF[left] = minSPF[right];maxSPF[left] = maxSPF[right];while (left < right && minSPF[left] < pivotValue){left++;}minSPF[right] = minSPF[left];maxSPF[right] = maxSPF[left];}minSPF[left] = pivotValue;maxSPF[left] = tempOfMaxSPF;int pivot = left;quickSortCows(first, pivot - 1);first = pivot + 1;}}int main(){//freopen("input.txt", "r", stdin);/* input */scanf("%d %d", &cows, &bottles);int cow;for (cow = 1; cow <= cows; cow++){scanf("%d %d", &minSPF[cow], &maxSPF[cow]);}int bottle;for (bottle = 1; bottle <= bottles; bottle++){scanf("%d %d", &lotionSPF[bottle], &covers[bottle]);}/* sort */quickSortCows(1, cows);quickSortBottles(1, bottles);/* main loop: use bottles of lotions to cover cows */int cowsProtected = 0;cow = 1;for (bottle = 1; bottle <= bottles; bottle++){//insert cows whose minSPF less than lotionSPF into order listwhile (cow <= cows && minSPF[cow] <= lotionSPF[bottle]){insert(maxSPF[cow]);cow++;}//cover cows whose maxSPF bigger than lotionSPF in the list with lotionswhile (head != NULL && covers[bottle]){node *pTemp = head;head = head->pNext;if (pTemp->SPF >= lotionSPF[bottle]){covers[bottle]--;cowsProtected++;}free(pTemp);}}/* output */printf("%d", cowsProtected);return 0;}

0 0
原创粉丝点击