Sumsets

find a+b+c=d , 3sum problem 枚举d

http://poj.org/problem?id=2549

View Code
const int MM = 111111;
int N;
int num[MM];

void get_data() {
    int i,j,k;
    for(i=0;i<N;i++) scanf("%d",&num[i]);
}
//choose three number from a set,then a+b+c=0
void threesum(int n,int*val) {
    int i,j,k,a,b,c,tmp,l;
    sort(val,val+n);
    for(l=n-1;l>=0;l--) {
    for(i=0;i<n-2;i++) {
        if(i==l) continue;
        a=val[i], j=i+1, k=n-1;
        while(j<k) {
            if(j==l) j++;
            if(k==l) k--;
            if(j>=k) break;
            b=val[j], c=val[k], tmp=a+b+c;
            if(tmp==val[l]) {
    //            printf("%d %d %d\n",a,b,c);
                printf("%d\n",val[l]);
                return;
            }
            else if(tmp>val[l]) k--;
            else j++;
        }
    }
    }
    puts("no solution");
}

void solve() {
    int i,j,k;
    threesum(N,num);
}
int main() {
    while(scanf("%d",&N),N) get_data(),solve();
    return 0;
}

 

posted @ 2013-05-02 20:58  zhang1107  阅读(167)  评论(0编辑  收藏  举报