洛谷历险记 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函数的用法!

发布了24 篇原创文章 · 获赞 3 · 访问量 1899

猜你喜欢

转载自blog.csdn.net/z1261203654/article/details/104692564