Magic Triangle


Description

You have N sticks on your hands. When I show you a stick, you should tell me how many pairs of sticks on your hands can make a triangle with my stick.



Input

The first line is a positive integer T standing for the numbers of test cases. The first line of each test case is two positive integers N, M, standing for the number of sticks on your hands and the times I will show you a stick. The second line has N positive integers. Each stands for i-th length of a stick on your hands. The i-th stick's length is li. Then M lines follow .Each is a positive integer Ki indicating the length of stick that I show you.(1<=T<=100,2<=N<=2000,1<=M<=100000,1<=li<=50000,1<=ki<=100000)

Output

For each stick I show you, output the number of pair that can make a triangle with this stick. Each output should be in one line.

Sample Input

2
3 2
2 4 6
5
16
3 1
12 12 18
12

Sample Output

3
0
3



题目意思:

本题就给n个点,放在一个数组a里面。然后给一个数,问从a里面取出两个数能否构成一个三角形,能组成三角形的个数。

本题暴力肯定是不行的,时间复杂度太高。本题的复杂度最大O(n*n)+O(m);而本题我用的预处理此处的复杂度为n*n,然后输入m个数就是o(1)了。这题在比赛的时候始终不知道怎么做。

最后采取一个里散化点的范围然后就一个查找。代码比较简单,也很容易理解。只要知道区间离散化就好。

代码:




#include<iostream>
#include<fstream>
#include<iomanip>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<sstream>
#include<cassert>
using namespace std;
//#define LL __int64

#ifdef __int64
typedef __int64 LL;
#else
typedef long long LL;
#endif

int Abs(int t){
  if(t<0) return 0-t;
  return t;
}
int a[2005];
int b[50000*2+2];
int sum[50000*2+2];
int main() {
    int t;
    cin>>t;

    while(t--) {
        int n,m;
        scanf("%d%d",&n,&m);
        for(int i=0; i<n; i++) {
            scanf("%d",&a[i]);
        }

        memset(b,0,sizeof(b));
        for(int i=0; i<n; i++) {
            for(int j=i+1; j<n; j++) {
                int mi=Abs(a[i]-a[j]);
                int ma=a[i]+a[j];
                b[mi+1]++;
                b[ma]--;
            }
        }

        // for(int i=0;i<n;i++){
        //   cout<<b[i]<<endl;
        // }

        sum[0]=b[0];
        for(int i=1; i<50000*2+2; i++) {
            sum[i]=sum[i-1]+b[i];
        }

        int x;
        for(int i=0; i<m; i++) {
            scanf("%d",&x);
            printf("%d\n",sum[x]);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值