[poj] 2549 Sumsets || 双向bfs

原题

在集合里找到a+b+c=d的最大的d。


显然枚举a,b,c不行,所以将式子移项为a+b=d-c,然后双向bfs,meet int the middle。

#include<cstdio>
#include<algorithm>
#define N 1010
using namespace std;
int a[N],n,cnt;
bool b;
struct hhh
{
    int data,x,y;
    bool operator < (const hhh &b) const
	{
	    return data<b.data;
	}
}ans[500010];

int read()
{
    int ans=0,fu=1;
    char j=getchar();
    for (;(j<'0' || j>'9') && j!='-';j=getchar()) ;
    if (j=='-') fu=-1,j=getchar();
    for (;j>='0' && j<='9';j=getchar()) ans*=10,ans+=j-'0';
    return ans*fu;
}

int main()
{
    while (~scanf("%d",&n) && n)
    {
	b=0;
	cnt=0;
	for (int i=1;i<=n;i++)
	    a[i]=read();
	sort(a+1,a+n+1);
	for (int i=1;i<=n;i++)
	    for (int j=i+1;j<=n;j++)
		ans[++cnt].data=a[i]+a[j],ans[cnt].x=a[i],ans[cnt].y=a[j];
	sort(ans+1,ans+cnt+1);
	for (int i=n;i>=1 && !b;i--)
	    for (int j=n;j>=1 && !b;j--)
		if (i!=j)
		{
		    hhh* qwq=lower_bound(ans+1,ans+cnt+1,(hhh){a[i]-a[j],0,0});
		    while (qwq->data==a[i]-a[j])
		    {
			if (qwq->x!=a[j] && qwq->y!=a[j] && qwq->x!=a[i] && qwq->y!=a[i])
			{
			    printf("%d
",a[i]);
			    b=1;
			    break;
			}
			else qwq++;
		    }
		}
	if (!b) printf("no solution
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/mrha/p/8018352.html