HDOJ 5265 pog loves szh II

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5265

题意很简单,给我们n个数,和一个p,从n个数中取两个数A和B,问我们能够得到的最大的(A+B)%p为多少。

这道题我们可以用贪心过,首先先对每个数取余,我们贪心的策略就是枚举每一位x,看能不能找到一个值比p-x-1相等或小的值,找到最大的这个值,如果没有,说明找不到一个数和它相加小于p,那么直接加最大的那个数。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL __int64
using namespace std;
const int maxn = 100005;
LL a[maxn],p;
int n;
void read(LL &x)
{
	int flag = 0;
	x = 0;
	char c = getchar();
	if(c == '-') flag = 1;
	while(c<'0' || c>'9')
	{
		if(c == '-') flag = 1;
		c = getchar();
	}
	while(c >= '0' && c <= '9')
		x = x*10+c-'0', c = getchar();
	if(flag) x = -x;
}
int main()
{
	while(scanf("%d%I64d",&n,&p) !=EOF)
	{
		for(int i=0; i<n; i++)
		{
			read(a[i]);
			a[i] %= p;
		}
		sort(a,a+n);
		LL ans = (a[n-1]+a[n-2])%p;
		//for(int i=0; i<n; i++) printf("%d ",a[i]);
		for(int i=0; i<n-1; i++)
		{
			LL mod = p-a[i]-1;
			int pos = upper_bound(a, a+i-1, mod)-a-1;
			if(pos == -1) ans = max(ans, (a[i]+a[n-1])%p);
			else ans = max(ans, (a[i]+a[pos])%p);
		}
		printf("%d\n",ans);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值