您的位置:首页 > 其它

HDU - 5265 pog loves szh II (二分或者贪心)

2017-08-10 18:36 435 查看
这题有两种做法,一种是二分,我很快就想到了(nlogn的复杂度,10^6的n).

第二种就是贪心了,我觉得这个不那么容易想到,好像速度要快一些.

首先,我们找答案的两个数x,y,有两种,一种是x+y>p,一种是x+y< p ,(读入时把每一个都mod p) 那么第一种如果存在,那么最大值一定是数组最大值加次大值的mod.第二种的最大值,就是我们要关心的事情了.

第一种我们直接使用二分,每一个a[i],我们都二分的搜索他的最大希望值p-a[i]-1,这个二分是我手写的,因为不知道upperbound和lowerbound怎么在这里使用了,找到小于等于希望值的第一个数,这是显然的思路.当然这题我wa了几万次,问题就出在这里了,没有考虑清楚如果搜索到的位置和i重合时要特殊处理,如果找到位置重合但不是0,那么就把找到位置左移一个,如果是0,那就不算他了(因为如果要算,他也只能是第一种情况).

第二种是一种逼近的贪心思想,每一次都要找到使a[i]+temp< p最大的temp值,也就是从数组的两头夹过来,注意处理接头时,我也wa了很多次.

代码见下

/*  xzppp  */
#include <iostream>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <list>
#include <math.h>
#include <iomanip>
using namespace std;
#define FFF freopen("in.txt","r",stdin);freopen("out.txt","w",stdout);
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mp make_pair
typedef long long  LL;
typedef unsigned long long ULL;
const int MAXN = 100000;
const int  INF = 0x7fffffff;
const int MOD = 1e9+7;
LL a[MAXN+17];
int main()
{
//FFF
LL n,p;
while(scanf("%lld%lld",&n,&p)!=EOF)
{
memset(a, 0, sizeof(a));
LL ans = -INF;
for (int i = 0; i < n; ++i)
{
scanf("%lld",a+i);
a[i] = a[i]%p;
}
sort(a, a+n);
ans = (a[n-1]+a[n-2])%p;
for (int i = 0; i < n; ++i)
{
LL temp = p-a[i]-1;
int l = 0,r = n;
while(r-l>1)
{
int mid = (l+r)/2;
if(a[mid]>temp)
r = mid;
else
l = mid;
}
if(l!=i)
ans = max((a[i]+a[l])%p,ans);
else if(l==0)
ans = max((a[i]+a[n-1])%p,ans);
else
ans = max((a[i]+a[l-1])%p,ans);
}
printf("%lld\n",ans);
}
return 0;
}


/*  xzppp  */
#include <iostream>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <list>
#include <math.h>
#include <iomanip>
using namespace std;
#define FFF freopen("in.txt","r",stdin);freopen("out.txt","w",stdout);
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mp make_pair
typedef long long  LL;
typedef unsigned long long ULL;
const int MAXN = 100000;
const int  INF = 0x7fffffff;
const int MOD = 1e9+7;
LL a[MAXN+17];
int main()
{
//FFF
LL n,p;
while(scanf("%lld%lld",&n,&p)!=EOF)
{
memset(a, 0, sizeof(a));
LL ans = -INF;
for (int i = 0; i < n; ++i)
{
scanf("%lld",a+i);
a[i] = a[i]%p;
}
sort(a, a+n);
ans = (a[n-1]+a[n-2])%p;
int rt = n-1;
for (int i = 0; i < n&&i <rt; ++i)
{
while(a[i]+a[rt]>=p) rt--;

4000
if(i<rt) ans = max(ans,(a[i]+a[rt])%p);
}
printf("%lld\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm