poj 1186 分类: poj 2015-08-08 22:28 4人阅读 评论(0) 收藏


似乎是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;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-08-08 22:28  <Dash>  阅读(182)  评论(0编辑  收藏  举报