Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iomanip>
- #include <algorithm>
- #include <vector>
- #include <sstream>
- #include <cstdlib>
- using namespace std;
- struct Point{
- int x, y, index;
- Point(int x, int y, int idx){
- this->x = x;
- this->y = y;
- this->index = idx;
- }
- };
- void createCombinations(vector <int> arr, string out, int i, int n, int k, vector <string> &results){
- if(k == 0){
- results.push_back(out);
- return;
- }
- for(int j = i; j < n; j++){
- createCombinations(arr, out + " " + to_string(arr[j]), j + 1, n, k - 1, results);
- }
- }
- double calculateDistance(int x1, int y1, int x2, int y2){
- return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
- }
- bool compareDistance(pair <Point, Point> p1, pair <Point, Point> p2){
- return calculateDistance(p1.first.x, p1.first.y, p1.second.x, p1.second.y) < calculateDistance(p2.first.x, p2.first.y, p2.second.x, p2.second.y);
- }
- void solve(vector <Point> houses){
- const int n = houses.size();
- vector <pair<Point, Point>> points;
- vector <double> distances;
- vector <bool> flag(n, false);
- vector <int> index(n * (n - 1) / 2);
- vector <string> combinations;
- for(int i = 0; i < index.size(); i++){
- index[i] = i;
- }
- createCombinations(index, "", 0, n * (n - 1) / 2, n / 2, combinations);
- for(int i = 0; i < n; i++){
- for(int j = i + 1; j < n; j++){
- points.push_back({houses[i], houses[j]});
- }
- }
- for(int i = 0; i < n * (n - 1) / 2; i++){
- distances.push_back(calculateDistance(points[i].first.x, points[i].first.y, points[i].second.x, points[i].second.y));
- }
- int pair;
- bool valid;
- double sum = 10e9, temp = 0;
- for(int i = 0; i < combinations.size(); i++){
- fill(flag.begin(), flag.end(), false);
- temp = 0;
- valid = true;
- stringstream ss(combinations[i]);
- while(ss >> pair){
- if(!flag[points[pair].first.index] && !flag[points[pair].second.index]){
- temp += distances[pair];
- flag[points[pair].first.index] = true;
- flag[points[pair].second.index] = true;
- }else{
- valid = false;
- break;
- }
- }
- if(valid){
- sum = min(sum, temp);
- }
- ss.clear();
- }
- cout << fixed << setprecision(2) << sum << " ";
- }
- int main(){
- int n, x, y, index;
- vector <Point> houses;
- string temp;
- getline(cin, temp);
- stringstream stream(temp);
- while(stream >> n){
- index = 0;
- houses.reserve(2 * n);
- for(int i = 0; i < 2 * n; i++){
- stream >> x >> y;
- Point p(x, y, index++);
- houses.push_back(p);
- }
- solve(houses);
- houses.clear();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement