#includecstdio#includecmath#includecstdlibusing namespace std;templatetypename Tinline void readT&x x=0; char s=getchar; bool f=false; while!s=0&&s=9 ifs==- f=true; s=getchar; whiles=0&&s=9 x=
#include
struct node { int x, y, w; };
int numOfWeights; double ans, ansX, ansY; node weights[N];
// Read template
template
// Calculate potential energy double calculatePotentialEnergy(double x, double y) { double energy=0.0; for(int i=1; i<=numOfWeights; i++) energy+=sqrt((x-weights[i].x)(x-weights[i].x)+(y-weights[i].y)(y-weights[i].y))*weights[i].w; return energy; }
// Solve using simulated annealing algorithm void solve() { // Set initial temperature and cooling factor double temperature = 1e5; double coolingFactor = 0.996;
while(temperature > 1e-18)
{
// Generate a random move
double tmpX = ansX + (rand() + rand() - RAND_MAX) * temperature;
double tmpY = ansY + (rand() + rand() - RAND_MAX) * temperature;
// Calculate potential energy of the new move
double tmpEnergy = calculatePotentialEnergy(tmpX, tmpY);
// Calculate the difference in energy
double energyDifference = tmpEnergy - ans;
// Accept the move if it improves the solution or with a certain probability
if(energyDifference < 0.0 || exp(-energyDifference / temperature) * RAND_MAX > rand())
{
ans = tmpEnergy;
ansX = tmpX;
ansY = tmpY;
}
// Cool down the temperature
temperature *= coolingFactor;
}
}
int main() { srand(rand());
// Read the number of weights and their coordinates and weights
read(numOfWeights);
for(int i=1; i<=numOfWeights; i++)
{
read(weights[i].x);
read(weights[i].y);
read(weights[i].w);
ansX += weights[i].x;
ansY += weights[i].y;
}
// Calculate the initial average position and potential energy
ansX /= numOfWeights;
ansY /= numOfWeights;
ans = calculatePotentialEnergy(ansX, ansY);
// Perform the solve function multiple times to improve the solution
for(int i=1; i<=4; i++)
solve();
// Print the final average position
printf("%.3lf %.3lf\n", ansX, ansY);
return 0;
原文地址: https://www.cveoy.top/t/topic/ixNF 著作权归作者所有。请勿转载和采集!