演算法競賽入門經典 第二版 習題5-6 對稱軸 Symmetry uva1595
阿新 • • 發佈:2018-12-30
思路:動用兩個容器,一個容器存下所有座標(vector< pair< int>,int>用pair存下點的x、y座標),另一個容器記錄按縱座標分類的點的橫座標(map< int, set< int> >關鍵字是縱座標,set裡存的是對應縱座標的橫座標,set有序,因此是由小到大排列)。對第一容器排序,取最大和最小的橫座標,其平均值即為可能的對稱軸。接下來只要判斷是否所有縱座標相同的點其從兩側到中間每一對橫座標都等於那個對稱軸即可。
程式碼:
#include <iostream>
#include <string>
#include <cstdio>
#include <iomanip>
#include <map>
#include <set>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
int UNINIT = -20000;
map<int, set<int> > ydata;//(y,x)
vector<pair<int, int> > data;
double ans;
bool judge()
{
ans = data[0 ].first*0.5+data[data.size()-1].first*0.5;
for(map<int, set<int> >::iterator it = ydata.begin(); it!=ydata.end(); ++it)
{
set<int>::iterator op = (it->second).begin();
set<int>::iterator ed = --(it->second).end();
for(int i=0; i<=(it->second).size()/2 ; i++, op++, ed--)
{
if(*op*0.5+*ed*0.5!=ans)
{
return false;
}
}
}
return true;
}
int main()
{
int T;
cin >> T;
while(T--)
{
data.clear();
ydata.clear();
int n;
cin >> n;
for(int i=0; i<n; i++)
{
int x, y;
cin >> x >> y;
data.push_back(make_pair(x, y));
ydata[y].insert(x);
}
sort(data.begin(), data.end());
if(judge())
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
return 0;
}