UVA1152 4 Values whose Sum is 0

meet-in-the-middle模板题。。。

复杂度太大了,我们就要想想能不能折半,折半后的复杂度如果刚好能过的话就是折半了。。。

这道题要做的就是预处理出所有的\(a_i+b_j\),然后用一个表来存下来。

然后就可以再枚举所有的\(c_i+d_j\),看看是否有等于\(-(a_i+b_j)\)的,如果有的话将个数计入答案。

如果用map来做的话因为常数大还过不了。

上github翻了蓝书的代码,居然用了个数组解决了,直接sort、upper_bound和lower_bound乱用就求出答案来了。。。

代码:

#include<cstdio>
#include<algorithm>
const int maxn = 4005;
int a[maxn], b[maxn], c[maxn], d[maxn];
int e[16000005];
int n, ans, cnt;

int read()
{
    int ans = 0, s = 1;
    char ch = getchar();
    while(ch > '9' || ch < '0'){ if(ch == '-') s = -1; ch = getchar(); }
    while(ch >= '0' && ch <= '9') ans = (ans << 3) + (ans << 1) + ch - '0', ch = getchar();
    return s * ans;
}
void solve()
{
    ans = 0;
    cnt = 0;
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
        {
            int res = a[i] + b[j];
            e[++cnt] = res;
        }
    }
    std::sort(e + 1, e + cnt + 1);// 直接排序走一波
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
        {
            int res = c[i] + d[j];
            int temp = std::upper_bound(e + 1, e + n * n + 1, -res) - std::lower_bound(e + 1, e + n * n + 1, -res);// 直接算出有多少个,第一次见这么用
            ans += temp;
        }
    }
}
int main()
{
    int T = read();
    while(T--)
    {
        n = read();
        for(int i = 1; i <= n; i++)
        {
            a[i] = read(), b[i] = read(), c[i] = read(), d[i] = read();
        }
        solve();
        printf("%d\n", ans);
        if(T) printf("\n");
    }
    return 0;
}

转载于:https://www.cnblogs.com/Garen-Wang/p/9853223.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值