【洛谷P2134 百日旅行】 题解

题目描述

小明和小红还剩下N天的假期,小明可以安排旅行的计划。如果连续X天旅游,小明需要花旅行费用PXX元;如果连续X天不旅游,小明需要请小红吃饭,花费为Q*X元。(P,Q都是输入的常数)

请你帮小明写一个程序,计算出假期里他至少需要花费多少元。


只会贪心做法....

首先可以明确一点,在天数相同的情况下,吃饭天数连不连续不重要,旅行天数能分开就分开

于是我们可以直接枚举吃饭天数 \(i\),剩下的 \(n-i\) 天旅游可以分成 \(i+1\) 段,然后统计即可。

时间复杂度 \(O(n)\)

// Problem: P2134 百日旅行
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P2134
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
//#define mo
int n, m, i, j, k; 
int a, b, ans, p, q; 

int tra(int x, int y)
{
	a=x/y; b=x%y;
	return (y-b)*p*a*a+b*p*(a+1)*(a+1); 
}

signed main()
{
//	freopen("tiaoshi.in", "r", stdin); 
//	freopen("tiaoshi.out", "w", stdout); 
	n=read(); p=read(); q=read(); 
	ans=n*n*p; 
	for(i=1; i<=n; ++i) ans=min(ans, q*i+tra(n-i, i+1)); 
	printf("%lld", ans); 
	return 0; 
}

posted @ 2021-11-14 16:50  zhangtingxi  阅读(63)  评论(0编辑  收藏  举报