72分折半搜索求条QAQ
查看原帖
72分折半搜索求条QAQ
907119
koukilee楼主2024/8/13 11:54
/* The code is from koukilee*/
#include <cstdio>
#include <unordered_map>
#include <algorithm>

using i32 = int; using i64 = long long; // std::mt19937 rd(time(0));
constexpr i64 MAXN = 1010100, mod = 1e9 + 7, INF = 992009100720100812; 

//static char buf[1000000],*p1=buf,*p2=buf,obuf[1000000],*p3=obuf;
//#define getchar() p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++
//#define putchar(x) (p3-obuf<1000000)?(*p3++=x):(fwrite(obuf,p3-obuf,1,stdout),p3=obuf,*p3++=x)
inline void read (i64 &sum) noexcept {
    i64 tf = 0; char ch = getchar(); sum = 0;
    while (ch < '0' || ch > '9') tf = ch == '-' ? 1 : 0, ch = getchar();
    while (ch >= '0' && ch <= '9') sum = (sum << 1) + (sum << 3) + (ch ^ 48), ch = getchar();
    (tf) && (sum =- sum);
}template <typename i64,typename ...Args>
inline void read (i64 &tmp, Args &...tmps) noexcept{read(tmp); read(tmps...);}
void printt (i64 x) noexcept {if(x >= 10) printt(x / 10); putchar(x % 10 + '0');} 
inline void print (i64 x) noexcept{x < 0 ? putchar('-'), printt(-x) : printt(x);}
inline void put (i64 x) noexcept{print(x), putchar('\n');}

inline i64 min(i64 a, i64 b) noexcept{return a < b ? a : b;}

i64 n, m, s[MAXN], ans = INF;
std::unordered_map<i64, i64> p;

void dfs(i64 step, i64 sum, i64 cnt, i64 maxx) noexcept{
    if (sum > m || cnt >= ans)
        return;

    if (sum == m) {
        ans = cnt;
        return;
    }

    if (step > maxx){
        if (maxx == (n >> 1))
            p[sum] = !p[sum] ? cnt + 1 : min(p[sum], cnt + 1);
        if (p[m - sum] && maxx == n && m - sum >= 0)
            ans = min(ans, p[m - sum] + cnt - 1);
        return;
    }

    dfs(step + 1, sum, cnt, maxx);
    dfs(step + 1, sum + s[step], cnt, maxx);
    dfs(step + 1, sum + (s[step] >> 1), cnt + 1, maxx);
}

int main() noexcept{
    read(n, m); m <<= 1;
    
    for (i32 i = 1; i <= n; i++)
        read(s[i]), s[i] <<= 1;

    std::sort(s + 1, s + n + 1, [&](i64 a, i64 b) noexcept{
        return a > b ;
    });
    
    dfs(1, 0, 0, n >> 1), dfs((n >> 1) + 1, 0, 0, n);

    put(ans == INF ? -1 : ans);
    //fwrite(obuf,p3-obuf,1,stdout);
    return 0;
}
2024/8/13 11:54
加载中...