Keep the Customer Satisfied poj 2786

按照截止时间排序,然后依次完成订单,如果发现无法完成订单,则从之前的订单和当前的订单中选出耗时最大的订单,放弃这个订单,这样所选订单就可以在规定时间内完成了,可以用数学归纳法证明该选择是最优的。


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
#include <cctype>
#include <utility>   
#include <map>
#include <string>  
#include <climits> 
#include <set>
#include <string> 
#include <sstream>
#include <utility>
#include <ctime>
 
using std::priority_queue;
using std::vector;
using std::swap;
using std::stack;
using std::sort;
using std::max;
using std::min;
using std::pair;
using std::map;
using std::string;
using std::cin;
using std::cout;
using std::set;
using std::queue;
using std::string;
using std::istringstream;
using std::make_pair;
using std::greater;

const int MAXN(800010);

struct HEAP
{
	int arr[MAXN];
	int size;
	void init()
	{
		size = 0;
	}

	void sink(int sour)
	{
		int temp = arr[sour];
		int son = sour << 1;
		while(son <= size)
		{
			if(son < size && arr[son+1] > arr[son])
				++son;
			if(arr[son] <= temp)
				break;
			arr[sour] = arr[son];
			sour = son;
			son <<= 1;
		}
		arr[sour] = temp;
	}

	void swim(int sour)
	{
		int temp = arr[sour];
		int p = sour >> 1;
		while(p >= 1 && arr[p] < temp)
		{
			arr[sour] = arr[p];
			sour = p;
			p >>= 1;
		}
		arr[sour] = temp;
	}

	void push(int value)
	{
		arr[++size] = value;
		swim(size);
	}

	int &top()
	{
		return arr[1];
	}

	void pop()
	{
		arr[1] = arr[size--];
		sink(1);
	}

	bool empty()
	{
		return size == 0;
	}
};

HEAP heap;

struct NODE
{
	int q, d;
	friend bool operator < (const NODE &op1, const NODE &op2)
	{
		return op1.d < op2.d;
	}
};

NODE node[MAXN];

int main()
{
	int n;
	while(~scanf("%d", &n))
	{
		for(int i = 1; i <= n; ++i)
		{
			scanf("%d%d", &node[i].q, &node[i].d);
		}
		sort(node+1, node+1+n);
		int ans = n, cur = 0;
		heap.init();
		for(int i = 1; i <= n; ++i)
		{
			heap.push(node[i].q);
			cur += node[i].q;
			if(cur > node[i].d)
			{
				--ans;
				cur -= heap.top();
				heap.pop();
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}


你可能感兴趣的:(Keep the Customer Satisfied poj 2786)