您的位置:首页 > 其它

poj 2549 折半枚举+二分

2015-07-17 16:54 260 查看
三重循环肯定TLE,所以采用“折半枚举”的方法+二分查找来提高速度,不同的是需要保存两个下标用来判定是否有重复元素。

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

const int N = 1000;
int a
;
int n, cnt;

struct Node
{
int ai, aj, v;
bool operator < ( const Node & o ) const
{
return v < o.v;
}
} node[N * N];

void solve()
{
for ( int i = n - 1; i > 0; i-- )
{
for ( int j = i - 1; j >= 0; j-- )
{
Node tmp;
tmp.v = a[i] - a[j];
int pos = lower_bound( node, node + cnt, tmp ) - node;
while ( node[pos].v == tmp.v )
{
if ( node[pos].ai != a[i] && node[pos].ai != a[j]
&& node[pos].aj != a[i] && node[pos].aj != a[j] )
{
printf("%d\n", a[i]);
return ;
}
pos++;
}
}
}
printf("no solution\n");
}

int main ()
{
while ( scanf("%d", &n) != EOF )
{
if ( n == 0 ) break;
cnt = 0;
for ( int i = 0; i < n; i++ )
{
scanf("%d", a + i);
for ( int j = i - 1; j >= 0; j-- )
{
node[cnt].ai = a[i];
node[cnt].aj = a[j];
node[cnt].v = a[i] + a[j];
cnt++;
}
}
sort( node, node + cnt );
node[cnt].v = 999999999;
sort( a, a + n );
solve();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: