百炼 6045 开餐馆问题

该题目类似于背包,用了一种动态规划的思想。
此题一开始犯了一个错,search返回下标包含0的情况与a[0]重叠了,后来从1开始存就没问题了。代码如下(如有错误或者不够简练的地方,请各位大佬批评指正):
// restuarant.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#pragma warning(disable:4996)
struct node
{
	int m;
	int p;
}node[100];
int a[1000000];
int n, k;
int search(int s)//对应位置有没有点,如果有的话返回对应饭馆的下标,没有则返回0
{
	for (int j = 1; j < n+1; j++)
	{
		if (node[j].m == s)
		{
			return j;
		}
	}
	return 0;
}

int max(int i, int j)
{
	if (i < j)
		return j;
	else
		return i;
}

int main()
{
	
	scanf("%d", &n);
	scanf("%d", &k);
	for (int i = 1; i < n+1; i++)
	{
		scanf("%d", &node[i].m);
	}
	for (int i = 1; i < n+1; i++)
		scanf("%d", &node[i].p);
	//for (int j = 0; j < n; j++)
	//	printf("%d %d\n", node[j].m, node[j].p);
	a[0] = 0;
	int len = node[n].m;
	for (int q = 1; q <= len; q++)
	{
		if (search(q) == 0)
			a[q] = a[q - 1];
		else
		{
			int price;
			if (q < k)
				price = a[0];//即为0
			else
				price = a[q - k];
			a[q] = max(a[q - 1], price + node[search(q)].p);
		}
	}
	printf("%d", a[len]);
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_34430032/article/details/80065940