折半枚举+3SUM--poj2549

来源:互联网 发布:万能视频修复软件 编辑:程序博客网 时间:2024/05/21 09:18

3SUM

Suppose the input array is S[0..n-1]. 3SUM can be solved inO(n^2) time by inserting each numberS[i] into a hash table, and then for each indexi andj, checking whether the hash table contains the integer-S[i]-S[j].

Alternatively, the algorithm below first sorts the input array and then tests all possible pairs in a careful order that avoids the need tobinary search for the pairs in the sorted list, again achieving O(n^2) time, as follows.[1]

sort(S); for i=0 to n-3 do    a = S[i];    k = i+1;    l = n-1;    while (k<l) do       b = S[k];       c = S[l];       if (a+b+c == 0) then          output a, b, c;          exit;       else if (a+b+c > 0) then          l = l - 1;       else          k = k + 1;       end       end end


下面是代码:

#include<iostream>#include<cstdio>#include<algorithm>using namespace std;int N;int a[1010];void solve(){    bool flag=false;    int tmp;    for(int i=N; i>=1; i--)    {        tmp=a[i];        for(int j=1; j<=N-2; j++)        {            if(i==j)            continue;            int s=a[j];            int k=j+1;            int l=N;            while(k<l)            {                if(s+a[k]+a[l]==tmp&&k!=i&&l!=i)                {                    flag=true;                    break;                }                else if(s+a[k]+a[l]>tmp)                    l-=1;                else                    k+=1;            }            if(flag)                break;        }        if(flag)            break;    }    if(flag)        cout<<tmp<<endl;    else cout<<"no solution"<<endl;}int main(){    while(cin>>N,N)    {        for(int i=1; i<=N; i++)            scanf("%d",&a[i]);        if(N<=3)        {            cout<<"no solution"<<endl;            continue;        }        sort(a+1,a+N+1);        solve();    }    return 0;}