1. 程式人生 > >(計蒜客)蒜頭君撿石子(堆 優先佇列)

(計蒜客)蒜頭君撿石子(堆 優先佇列)

解題思路:

這題可以用優先佇列解決

我們把所有石子距離自己的距離和石頭可以扔出的最遠距離構成一個優先順序佇列

這個佇列的優先順序為距離自己的距離,如果距離自己的距離相同,那麼優先順序為可以扔出的最遠距離

這樣我們可以構建出堆

#include <iostream>
#include <algorithm>
using namespace std;

struct Stone
{
	int disFromMe;
	int distance;
};

class StoneTree {
private:
	Stone* data;
	int size;

	void update(int pos, int n) {
		int min_pos = pos;
		int lchild = 2 * pos + 1;
		int rchild = 2 * pos + 2;
		
		if (lchild < n && data[lchild].disFromMe <= data[min_pos].disFromMe) {
			if (data[lchild].disFromMe == data[min_pos].disFromMe) {
				if (data[lchild].distance < data[min_pos].distance) {
					min_pos = lchild;
				}
			}
			if (data[lchild].disFromMe < data[min_pos].disFromMe) {
				min_pos = lchild;
			}
		}
		if (rchild < n && data[rchild].disFromMe <= data[min_pos].disFromMe) {
			if (data[rchild].disFromMe == data[min_pos].disFromMe) {
				if (data[rchild].distance < data[min_pos].distance) {
					min_pos = rchild;
				}
			}
			if (data[rchild].disFromMe < data[min_pos].disFromMe) {
				min_pos = rchild;
			}
		}

		if (min_pos != pos) {
			swap(data[min_pos], data[pos]);
			update(min_pos, n);
		}
	}

public:
	StoneTree(int length_data) {
		data = new Stone[length_data];
		size = 0;
	}
	~StoneTree() {
		delete data;
	}

	Stone top() {
		return data[0];
	}

	int getSize() {
		return size+1;
	}

	void push(Stone value) {
		data[size] = value;
		int current = size;
		int father = (current - 1) / 2;

		if (size == 0) {
			size = size + 1;
			return;
		}

		while (data[current].disFromMe < data[father].disFromMe) {
			swap(data[current], data[father]);
			current = father;
			father = (current - 1) / 2;
		}

		while (data[current].disFromMe == data[father].disFromMe) {
			if (data[current].distance < data[father].distance) {
				swap(data[current], data[father]);
				current = father;
				father = (current - 1) / 2;
			}
			else {
				break;
			}
		}
		size = size + 1;
		return;
	}

	void pop() {
		swap(data[0], data[size - 1]);
		size = size - 1;
		update(0, size);
	}

	void show() {
		for (int i = 0; i < size; ++i) {
			cout << data[i].disFromMe << " " << data[i].distance << endl;
		}
	}
};

然後我們依次將結點出隊,然後判斷,如果出隊次序為奇數次,那麼就將這個結點距離自己的距離更新為 距離自己的距離+扔出的距離,然後放回佇列中,調整堆序性

如果出隊次序為偶數次,那麼直接不管即可

int main() {
	StoneTree stonetre(100001);
	int n;
	cin >> n;
	for (int i = 0; i < n; ++i) {
		Stone sto;
		cin >> sto.disFromMe >> sto.distance;
		stonetre.push(sto);
	}

	int index = 1;    //判斷出隊次序是奇數次還是偶數次
	while (stonetre.getSize() > 1) {  
		Stone tsto = stonetre.top();
		stonetre.pop();
		if (index % 2 == 1) {
			tsto.disFromMe =tsto.disFromMe + tsto.distance;
			stonetre.push(tsto);
			index++;
		}
		else {
			index++;
		}
	}

	cout << stonetre.top().disFromMe << endl;
	system("PAUSE");
	return 0;
}