Test instructions: Give a grid size in which to find a base station, so that the square of the distance between each user (Euclidean distance squared), and to any of the communication distance (Manhattan distance) the total distance (cost) the smallest. In fact, to each user's distance to the minimum, to the communication company to be as close as possible, distance is the price.
Idea: At first feel the need to try every point, calculate the cost, then compare the cost, find the best location of the base station. However, this is called an algorithm? Not even faster than the poor algorithm is not called algorithm! So we have to find a way to reduce the point of the search, the idea that the base station can not be built in a certain direction without users or communications companies, such as users and communications companies are in the x-coordinate 10 or more, and we are based on the x-coordinate 1, then there is no sense. So you can find the maximum and minimum x coordinates of the user and communication company, the maximum and minimum y coordinates. is less than the minimum, and greater than the largest do not have to search, and the middle of the calculation costs. Although AC, but still a little time-consuming, 87ms. Feel should consider the user's distance on the line, the afternoon to try again.
1#include <iostream>2#include <cmath>3#include <stdio.h>4 using namespacestd;5 intN, M, A, B;//grid N*m A User B communication company6 structPOS7 {8 intx, y;9}apos[1005],bpos[1005];Ten One Long LongComputeintMinxintMiny,intMaxxintMaxy) A { - Long Longminv=99999999; - for(intI=minx; i<maxx; i++) the { - for(intJ=miny; j<maxy; J + +) - { - Long Longtmp=0; + - for(intk=0; k<a; k++)//to the cost of a user +TMP + = (i-apos[k].x) * (i-apos[k].x) + (J-APOS[K].Y) * (J-apos[k].y); A intv=999999; at for(intk=0; k<b; k++)//The minimum cost to a company of B - if(ABS (i-bpos[k].x) +abs (J-BPOS[K].Y) <v) -V =abs (i-bpos[k].x) +abs (J-bpos[k].y); - - if(tmp+v<MINV) -MINV = tmp +v; in } - } to returnMINV; + } - the intMain () * { $ Panax Notoginseng //freopen ("Input.txt", "R", stdin); - intT, j=0; the +Cin>>T; A while(t--) the { + intminx=999999, miny=999999, maxx=-1, maxy=-1;//find the largest x and y in A and B, and the smallest x and y -Cin>>n>>m>>a>>b; $ for(intI=0; i<a; i++)//Enter User Location $ { -Cin>>apos[i].x>>apos[i].y; - if(apos[i].x<Minx) theMinx =apos[i].x; - if(apos[i].x>Maxx)WuyiMaxx =apos[i].x; the if(apos[i].y<miny) -Miny =apos[i].y; Wu if(apos[i].y>Maxy) -Maxy =apos[i].y; About } $ - for(intI=0; i<b; i++)//Enter your company location - { -Cin>>bpos[i].x>>bpos[i].y; A if(bpos[i].x<Minx) +Minx =bpos[i].x; the if(bpos[i].x>Maxx) -Maxx =bpos[i].x; $ if(bpos[i].y<miny) theMiny =bpos[i].y; the if(bpos[i].y>Maxy) theMaxy =bpos[i].y; the } -cout<<"Case #"<< ++j<<": "<<compute (Minx, Miny, Maxx, Maxy) <<Endl; in the } the return 0; About}
Base Station Location
Programming Beauty 2015 Qualifying Hihocoder Topic 3: Base Station location