Magic Triangle

来源:互联网 发布:网站美工招聘 编辑:程序博客网 时间:2024/06/05 18:10


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

23 22 4 65163 112 12 1812

Sample Output

303



题目意思:

本题就给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 __int64typedef __int64 LL;#elsetypedef long long LL;#endifint 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;}


0 0
原创粉丝点击