poj 1186


似乎是NOI 2001的题目,感觉很有意思。。。


Meet in the Middle (中途相遇法)


看起来 O(MN) 不可做,方程移项有真相: k1xp11+k2xp22+k3xp33=(k4xp44+k5xp55+k6xp66)

分别计算 :

k1xp11+k2xp22+k3xp33=W 的解数 fL(W)

k4xp44+k5xp55+k6xp66=W 的解数 fR(W)

那么 ans=fL(x)fR(x)

时间复杂度: O(MN/2)


另外注意使用 std::unique 函数之后的数组中每个值出现的次数与原数组不相同。。。


#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <iostream>
#include <algorithm>

template<class Num>void read(Num &x)
{
    char c; int flag = 1;
    while((c = getchar()) < '0' || c > '9')
        if(c == '-') flag *= -1;
    x = c - '0';
    while((c = getchar()) >= '0' && c <= '9')
        x = (x<<3) + (x<<1) + (c-'0');
    x *= flag;
    return;
}
template<class Num>void write(Num x)
{
    if(x < 0) putchar('-'), x = -x;
    static char s[20];int sl = 0;
    while(x) s[sl++] = x%10 + '0',x /= 10;
    if(!sl) {putchar('0');return;}
    while(sl) putchar(s[--sl]);
}
const int maxn = 10, maxm = 155, size = maxm*maxm*maxm;

int n, m, k[maxn], p[maxn];

int val[size], len, vlen, cnt[size];

long long ans = 0;

void count(int rem,int v)
{
    if(rem == 0)
    {
        val[++len] = v;
        return;
    }

    for(int i = 1; i <= m; i++)
    {
        int cal = k[rem];

        for(int j = 1; j <= p[rem]; j++) cal *= i;

        count(rem - 1, v + cal);
    }
}
#define find_in_val(x) std::lower_bound(val + 1, val + vlen + 1, x) - val
void prework()
{
    static int tmp[size];

    for(int i = 1; i <= len; i++) tmp[i] = val[i];

    std::sort(val + 1, val + len + 1);
    vlen = std::unique(val + 1, val + len + 1) - (val + 1); 

    for(int i = 1; i <= len; i++) cnt[find_in_val(tmp[i])] ++;
}

void dfs(int pos,int v)
{
    if(pos > n)
    {
        int t = find_in_val(-v);
        if(val[t] == -v) ans += cnt[t];
        return;
    }

    for(int i = 1; i <= m; i++)
    {
        int cal = k[pos];

        for(int j = 1; j <= p[pos]; j++) cal *= i;

        dfs(pos + 1, v + cal);
    }
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("1186.in","r",stdin);
    freopen("1186.out","w",stdout);
#endif

    read(n), read(m);
    for(int i = 1; i <= n; i++)
        read(k[i]), read(p[i]);

    count(n>>1, 0);

    prework();

    dfs((n>>1) + 1, 0);

    write(ans);

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值