编程介的小学生 2019-02-12 16:09 采纳率: 0.4%
浏览 238

数组的输出问题的一个数据结构的连续性的问题,怎么利用C语言

Problem Description
To help their clients deal with faulty Cash Machines, the board of The Planar Bank has decided to stick a label expressing sincere regret and sorrow of the bank about the failure on every ATM. The very same label would gently ask the customer to calmly head to the nearest Machine (that should hopefully
work fine).

In order to do so, a list of two-dimensional locations of all n ATMs has been prepared, and your task is to find for each of them the one closest with respect to the Euclidean distance.

Input
The input contains several test cases. The very first line contains the number of cases t (t <= 15) that follow. Each test cases begin with the number of Cash Machines n (2 <= n <= 10^5). Each of the next n lines contain the coordinates of one Cash Machine x,y (0 <= x,y <=10^9) separated by a space. No two
points in one test case will coincide.

Output
For each test case output n lines. i-th of them should contain the squared distance between the i-th ATM from the input and its nearest neighbour.

Sample Input
2
10
17 41
0 34
24 19
8 28
14 12
45 5
27 31
41 11
42 45
36 27
15
0 0
1 2
2 3
3 2
4 0
8 4
7 4
6 3
6 1
8 0
11 0
12 2
13 1
14 2
15 0

Sample Output
200
100
149
100
149
52
97
52
360
97
5
2
2
2
5
1
1
2
4
5
5
2
2
2
5

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-07 22:29
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    这是一个典型的距离计算问题,我们可以使用哈希表来存储每个点的位置和它到其他所有点的距离。然后对于每一个点,我们只需要查找它到已知最近点的距离,并将其平方加到答案中即可。

    以下是C语言实现:

    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAXN 100005
    
    int n;
    long long d[MAXN];
    
    void read() {
        scanf("%d", &n);
        for(int i = 1; i <= n; ++i)
            scanf("%lld %lld", &d[i], &d[i + n]);
    }
    
    void init() {
        for(int i = 1; i <= n * 2; ++i)
            d[i] = d[i - n];
    }
    
    double query(int x) {
        double ans = 0;
        int i = 1;
        while(i <= n && d[i] > 0) {
            if(x >= d[i]) {
                ans += d[i] * d[i];
                x -= d[i];
            }
            i *= 2;
        }
        return ans;
    }
    
    int main() {
        read();
        init();
        for(int i = 1; i <= n; ++i) {
            printf("%lld\n", query(d[2 * i]));
        }
        return 0;
    }
    

    这段代码首先读入测试用例的数量以及ATM的数量,然后初始化一个长度为2*n的数组d,其中d[i]表示第i个ATM离当前中心点的距离。接着对d数组进行处理,找出每两个相邻的ATM之间的最小距离并记录下来。最后,对于每一个ATM,我们都计算出其到中心点的距离,然后将这个距离与当前中心点到最近ATM的距离相减,得到新的距离。我们将这些新的距离平方后求和,即得到了最终的答案。

    评论

报告相同问题?