TOTALODD - Số lẻ hoàn toàn

Tác giả: RR

Ngôn ngữ: C++

#include <iostream>
#include <algorithm>

#define FOR(i,a,b)  for(int i=a; i<=b; i++)
#define FORD(i,a,b) for(int i=a; i>=b; i--)
using namespace std;

int n,a[500111],sl;
char s[20];

void dequy(int i,int gh,int now) {
    for(int u=1; u<=9; u+=2) {
        int x=now*10+u;
        if (i<gh) dequy(i+1,gh,x);
        else a[++sl]=x;
    }
}

void init() {
    FOR(l,1,8) dequy(1,l,0);
}

void solve() {
    int u=lower_bound(a+1,a+sl+1,n)-a-1; if (u<sl) u++;
    
    int res=a[u]+a[u]+1;
    a[0]=-a[sl]-1;
    int j=u;
    FOR(i,1,u) {
        if (i>j) break;
        if (a[i]>res) break;
        while (a[i]+a[j-1]>=n) j--;
        while (a[i]+a[j]>res) j--;
        if (a[i]+a[j]>=n) res=min(res,a[i]+a[j]);
    }
    printf("%d\n",res);
}

int main() {
    init();
    scanf("%s\n",&s);
    while (s[1]=='C') {
        scanf("%d",&n);
        solve();
        scanf("%s\n",&s);
    }
    return 0;
}

Download