1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
#include<iostream>
#include<map>
#include<cmath>
using namespace std;
pair<double,double> findNearest(multimap<char,pair<double,double>>,char,double,double);
int main()
{
multimap<char,pair<double,double>> buildings;
cout<<"Please input 20 buildings(type h or u or p) and their coordinates: "<<endl;
char c;
double x,y;
int i = 20;
while(cin>>c>>x>>y && i--)
{
buildings.insert({c,{x,y}});
}
cout<<"the 20 buildings and their coordinates are listed below:"<<endl;
for(auto iter = buildings.begin(); iter !=buildings.end(); ++iter)
{
switch(iter->first)
{
case 'h':
cout<<"Building Type: Hospital \t"<<"Location: x="<<iter->second.first<<" y="<<iter->second.second<<endl;
break;
case 'u':
cout<<"Building Type: University\t"<<"Location: x="<<iter->second.first<<" y="<<iter->second.second<<endl;
break;
case 'p':
cout<<"Building Type: Pharmacy \t"<<"Location: x="<<iter->second.first<<" y="<<iter->second.second<<endl;
break;
default:
break;
}
}
while(true)
{
cout<<"Please input the building type you want to search and your location:"<<endl;
cin>>c>>x>>y;
auto result=findNearest(buildings,c,x,y);
switch(c)
{
case 'h':
cout<<"The nearest hospital is at Location: x="<<result.first<<" y="<<result.second<<endl;
break;
case 'u':
cout<<"The nearest university is at Location: x="<<result.first<<" y="<<result.second<<endl;
break;
case 'p':
cout<<"The nearest pharmacy is at Location: x="<<result.first<<" y="<<result.second<<endl;
break;
default:
cout<<"Input Building Type Error!"<<endl;
}
cout<<"search again? (y for yes n for no):"<<endl;
string s;
cin>>s;
if(s[0] == 'n')
break;
}
}
pair<double,double> findNearest(multimap<char,pair<double,double>> buildings,char c,double x,double y)
{
auto lowerIter = buildings.lower_bound(c);
auto upperIter = buildings.upper_bound(c);
auto ret = lowerIter->second;
double nearestDistance = pow(ret.first-x,2)+pow(ret.second-y,2);
while(++lowerIter != upperIter)
{
double distance = pow(lowerIter->second.first-x,2)+pow(lowerIter->second.second-y,2);
if(distance<nearestDistance)
{
nearestDistance=distance;
ret = lowerIter->second;
}
}
return ret;
}
|