zoukankan      html  css  js  c++  java
  • 【[Offer收割]编程练习赛 14 A】小Hi和小Ho的礼物

    【题目链接】:http://hihocoder.com/problemset/problem/1505

    【题意】

    【题解】

    考虑Meet in the middle.
    因为两个数的和不是很大;
    直接用数组搞hash就好;

    for (int i = 1;i <= n)
         for (int j = i+1;j<= n;j++)
             cnt[a[i]+a[j]]++;


    弄出散列表
    然后再两重for 循环枚举另外两个元组
    k,l
    但是
    不能仅仅靠
    cnt[a[k]+a[l]来递增答案;
    因为可能有其他的元素t
    使得a[t]+a[k]==a[k]+a[l]
    或者是a[l]+a[t]==a[k]+a[l]
    要把这种情况排除掉;
    具体的
    记录a[l]有多少个,a[k]有多少个;
    然后把这种情况剔除掉就好了.


    【Number Of WA

    1

    【完整代码】

    #include <bits/stdc++.h>
    using namespace std;
    #define lson l,m,rt<<1
    #define rson m+1,r,rt<<1|1
    #define LL long long
    #define rep1(i,a,b) for (int i = a;i <= b;i++)
    #define rep2(i,a,b) for (int i = a;i >= b;i--)
    #define mp make_pair
    #define pb push_back
    #define fi first
    #define se second
    #define ms(x,y) memset(x,y,sizeof x)
    
    typedef pair<int,int> pii;
    typedef pair<LL,LL> pll;
    
    const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
    const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
    const double pi = acos(-1.0);
    const int N = 1100;
    
    LL a[N];
    int n,dic1[1009000],dic[2009000];
    
    int main()
    {
        //freopen("F:\rush.txt","r",stdin);
        ios::sync_with_stdio(false);
        cin >> n;
        rep1(i,1,n)
            cin >> a[i],dic1[a[i]]++;
        rep1(i,1,n)
            rep1(j,i+1,n)
                dic[a[i]+a[j]]++;
        LL ans = 0;
        rep1(i,1,n)
            rep1(j,i+1,n)
                {
                    int aa = dic1[a[j]],bb = dic1[a[i]];
                    int temp1 = aa-1,temp2 = bb-1;
                    if (a[i]==a[j]) temp1--,temp2--;
                    ans=ans+dic[a[i]+a[j]]-temp1-temp2-1;
                }
        cout << ans << endl;
        //printf("
    %.2lf sec 
    ", (double)clock() / CLOCKS_PER_SEC);
        return 0;
    }
    
  • 相关阅读:
    时空权衡之计数排序
    何时发生隐式类型转换
    常量指针与指针常量的区别
    虚函数有关面试题
    C++中数组定义及初始化
    InputStream类的available()方法
    FORK()函数
    面向对象三大基本特性,五大基本原则
    SpringMVC工作原理
    java文件的上传
  • 原文地址:https://www.cnblogs.com/AWCXV/p/7626416.html
Copyright © 2011-2022 走看看