Best way to efficiently find high density regions

前端 未结 3 1135
北荒
北荒 2021-02-02 11:59

Over the course of my coding, I have come across a problem as follows: Find the a region of fixed size in a 2D space that has the highest density of particles. The particles can

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-02 12:40

    I don't know what brute force method you use, but the most brute force way would be O(n^2 d^2), by iterating over every region in O(n^2) time, then count the number of particles in that region in O(d^2) time where d is the size of your region.

    This problem is exactly the same as this problem: Rat Attack, since the region area is fixed, and so the density is the same as the count, for which the solution is O(n^2 + k*d^2), where

    1. n is the size of the whole area (length of the side)
    2. k is the number of particles
    3. d is the size of each region (length of the side)

    by this algorithm:

    1. For each particle, update the count of the O(d^2) regions affected by this particle
    2. Iterate over all O(n^2) possible regions, find the maximum

    as shown in this code, I copy the relevant part here for your reference:

    using namespace std;
    
    int mat [1024 + 3] [1024 + 3]; // Here n is assumed to be 1024
    
    int main ()
    {
        int testCases; scanf ("%d", &testCases);
    
        while ( testCases-- ) {
    
            Set(mat, 0);
    
            int d; scanf ("%d", &d); // d is the size of the region
            int k; scanf ("%d", &k); // k is the number of particles
    
            int x, y, cost;
    
            for ( int i = 0; i < k; i++ ) {
                scanf ("%d %d %d", &x, &y, &cost); // Read each particle position
    
                // Update the count of the d^2 region affected by this particle
                for ( int j = max (0, x - d); j <= min (x + d, 1024); j++ ) {
                    for ( int k = max (0, y - d); k <= min (y + d, 1024); k++ ) mat [j] [k] += cost;
                }
            }
    
            int resX, resY, maxi = -1;
    
            // Find the maximum count over all regions
            for ( int i = 0; i < 1025; i++ ) {
                for ( int j = 0; j < 1025; j++ ) {
                    if ( maxi < mat [i] [j] ) {
                        maxi = mat [i] [j];
                        resX = i;
                        resY = j;
                    }
                }
            }
    
            printf ("%d %d %d\n", resX, resY, maxi);
    
        }
        return 0;
    }
    

    I've put my comments in the code to explain it to you.

提交回复
热议问题