一开始直接想求出每个距离,排序,二分,但超时了
但是直接存距离不会超时;跑了2400ms
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <stack>
#include <set>
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
#define ms(a, b) memset(a, b, sizeof(a))
#define pb push_back
#define mp make_pair
#define eps 0.0000000001
#define IOS ios::sync_with_stdio(0);cin.tie(0);
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
const int maxn = 3000+10;
int x[maxn], y[maxn];
int dis[maxn*maxn];
int n, q, r;
int cul(int i, int j)
{
return (y[j]-y[i])*(y[j]-y[i])+(x[j]-x[i])*(x[j]-x[i]);
}
void solve()
{
int cnt = 0;
for(int i = 0;i<n;i++) scanf("%d%d", &x[i], &y[i]);
for(int i = 0;i+1<n;i++){
for(int j = i+1;j<n;j++){
dis[cnt++] = cul(i, j);
}
}
sort(dis, dis+cnt);
int ans;
while(q--){
scanf("%d", &r);
int pos = upper_bound(dis, dis+cnt, r*r) - dis;
ans = 0;
ans += 2*pos;
ans += n;
printf("%.2f\n", (double)ans/(double)n);
}
printf("\n");
}
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
// IOS
while(~scanf("%d%d", &n, &q)&&n+q){
solve();
}
return 0;
}
更快的方法是预处理n^2 n(1)的查询
跑了391ms
代码如下
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
struct Node
{
int x,y;
}a[3005];
int b[40005];
int dis(Node a,Node b)
{
int xx=a.x-b.x;
int yy=a.y-b.y;
return ceil(sqrt(xx*xx+yy*yy));
}
int main()
{
int n,q;
while(scanf("%d%d",&n,&q)){
if(n==0&&q==0) break;
memset(b,0,sizeof(b));
for(int i=0;i<n;i++){
scanf("%d%d",&a[i].x,&a[i].y);
}
for(int i=0;i<n;i++)
for(int j=i;j<n;j++){
int temp=dis(a[i],a[j]);
if(i!=j) b[temp]+=2;
else b[temp]++;
}
for(int i=1;i<=40000;i++){
b[i]+=b[i-1];
}
for(int i=0;i<q;i++){
int r;
scanf("%d",&r);
printf("%.2f\n",double(b[r])/double(n));
}
printf("\n");
}
}