BD16. 浇花
描述
一个花坛中有很多花和两个喷泉。
喷泉可以浇到以自己为中心,半径为r的圆内的所有范围的花。
输入描述
第一行5个整数n,x1,y1,x2,y2表示花的数量和两个喷泉的坐标。输出描述
一个整数,r12 + r22 的最小值。示例1
输入:
2 -1 0 5 3 0 2 5 2
输出:
6
C 解法, 执行用时: 3ms, 内存消耗: 376KB, 提交时间: 2020-11-14
#include <stdio.h> #include <stdlib.h> #include <math.h> int sort(long* list, int len, int* arrangedindex){ //对list中的所有数使用归并排序方法从大到小排列,将这些数对应在list中的下标存储至arrangedindex if(len <= 0)return 0; if(len == 1){ arrangedindex[0] = 0; return 0; } int middle = len/2; long* newlist = (long*)(list + middle); int* arrng1 = (int*)malloc(middle*sizeof(int)); int* arrng2 = (int*)malloc((len - middle)*sizeof(int)); sort(list, middle, arrng1); sort(newlist, (len-middle), arrng2); int index = 0; int a,b; a = 0; b = 0; while(index < len){ if(a >= middle){ while(b < (len - middle)){ arrangedindex[index] = arrng2[b] + middle; b++; index++; } break; } if(b >= (len - middle)){ while(a < middle){ arrangedindex[index] = arrng2[a]; a++; index++; } break; } if(list[arrng1[a]] <= newlist[arrng2[b]]){ arrangedindex[index] = arrng2[b] + middle; b++; index++; continue; }else{ arrangedindex[index] = arrng1[a]; a++; index++; continue; } } free(arrng1); free(arrng2); return 0; } int main(){ int n,x1,y1,x2,y2; while(scanf("%d %d %d %d %d", &n, &x1, &y1, &x2, &y2) != EOF){ int i,j,k; int x,y; long* ftos1 = (long*)malloc(n*sizeof(long));//distence's square from floower to spring 1 long* ftos2 = (long*)malloc(n*sizeof(long));//distence's square from floower to spring 2 for(i = 0; i < n; i++){ scanf("%d %d", &x, &y); ftos1[i] = ((long)(x - x1))*((long)(x - x1)) + ((long)(y - y1))*((long)(y - y1)); ftos2[i] = ((long)(x - x2))*((long)(x - x2)) + ((long)(y - y2))*((long)(y - y2)); } int* arrangedindex = (int*)malloc(n*sizeof(int)); sort(ftos1, n, arrangedindex); long min = ftos1[arrangedindex[0]]; long maxof2 = -1; for(i = 0; i < n - 1; i++){ j = arrangedindex[i]; if(ftos2[j] > maxof2){ maxof2 = ftos2[j]; } k = arrangedindex[i+1]; if((ftos1[k] + maxof2) < min){ min = ftos1[k] + maxof2; } } if(ftos2[arrangedindex[n-1]] > maxof2){ maxof2 = ftos2[arrangedindex[n-1]]; } if(maxof2 < min){ min = maxof2; } printf("%ld\n", min); free(arrangedindex); free(ftos1); free(ftos2); } return 0; }
C++ 解法, 执行用时: 3ms, 内存消耗: 376KB, 提交时间: 2020-08-02
#include<bits/stdc++.h> using namespace std; int main() { int n, x1, y1, x2, y2; cin >> n >> x1 >> y1 >> x2 >> y2; vector<pair<long, long>> v; for (long i = 0; i < n; i++) { int xf, yf; cin >> xf >> yf; v.push_back(pair<long, long>(pow(xf - x1, 2) + pow(yf - y1, 2), pow(xf - x2, 2) + pow(yf - y2, 2))); } sort(v.begin(), v.end(), [](pair<long, long>& p1, pair<long, long>& p2) {return p1.first < p2.first;}); long ans = v[n - 1].first, jMax = v[n-1].second; for (int i = n - 2; i >= 0; i--) { ans = min(ans, (v[i].first + jMax)); jMax = max(jMax, v[i].second); } cout<<min(ans,jMax); return 0; }