洛谷歷險記 p1086 sort函數用法

#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>

using namespace std;

struct node
{
	int row;
	int column;
	int peanuts;
}a[500];

bool cmp(node a, node b) {
	if (a.peanuts > b.peanuts) {
		return true;
	}
	else {
		return false;
	}
}

int main() {
	int M, N, K;
	cin >> M >> N >> K;
	int n = 0;
	int temp;
	for (int i = 0; i < M; i++)
	{
		for (int j = 0; j < N; j++)
		{
			cin >> temp;
			a[n].row = i+1;
			a[n].column = j+1;
			a[n].peanuts = temp;
			n++;
		}
	}
	sort(a, a + M * N, cmp);//比較得開始位置,結束位置,比較方法(若返回true,則往前放)
	int cost = 0;
	int pos_r=0;//記錄當前位置
	int pos_c = 0;
	int ans=0;//記錄花生數
	n = 0;
	while (true)
	{
		if (n == 0) {
			if (K < a[n].row*2+1) {
				cout << 0 << endl;
				return 0;
			}
			else
			{
				K -= a[n].row+1;
				pos_r = a[n].row;
				pos_c = a[n].column;
				ans += a[n].peanuts;
				n++;
				continue;
			}
		}
		if ((abs)(a[n].column - pos_c) + (abs)(a[n].row - pos_r) + 1 + a[n].row <= K) {
			K -= ((abs)(a[n].column - pos_c) + (abs)(a[n].row - pos_r) + 1);
			pos_c = a[n].column;
			pos_r = a[n].row;
			ans += a[n].peanuts;
			n++;
		}
		else {
			break;
		}
	}
	cout << ans;
}

主要是搞懂了sort函數的用法!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章