欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > 欧拉计划 Project Euler61(循环的多边形数)题解

欧拉计划 Project Euler61(循环的多边形数)题解

2025/5/1 8:15:03 来源:https://blog.csdn.net/m0_53387935/article/details/147631450  浏览:    关键词:欧拉计划 Project Euler61(循环的多边形数)题解

欧拉计划 Project Euler 61 题解

  • 题干
  • 思路
  • code

题干

在这里插入图片描述

思路

先生成所有四位数的多边形数集合分类保存,然后dfs找即可

code

// 2512 1281 8128 2882 8256 5625 
// 28684
#include <bits/stdc++.h>using namespace std;using ll = long long;typedef vector<int> vi;
typedef pair<string, vi> PolySet;int triangle(int n) {return n * (n + 1) / 2;
}int square(int n) {return n * n;
}int pentagon(int n) {return n * (3 * n - 1) / 2;
}int hexagon(int n) {return n * (2 * n - 1);
}int heptagon(int n) {return n * (5 * n - 3) / 2;
}int octagon(int n) {return n * (3 * n - 2);
}bool isFourDight(int n) {return n >= 1000 && n <= 9999;
}bool Match(int a, int b) {return (a % 100) == (b / 100);
}bool dfs(vector<vi> &polySets, vector<int> &path, vector<bool> &used, int depth) {if (depth == 6) {return Match(path[5], path[0]);}for (int i = 0; i < 6; ++i) {if (used[i]) continue;for (int num : polySets[i]) {if (Match(path.back(), num)) {used[i] = true;path.push_back(num);if (dfs(polySets, path, used, depth + 1)) return true;path.pop_back();used[i] = false;}}}return false;
}void solve() {map<string, vi> polyNumbers;for (int n = 1; ; ++n) {int t = triangle(n);if (t > 9999) break;if (isFourDight(t)) polyNumbers["triangle"].push_back(t);}for (int n = 1; ; ++n) {int t = square(n);if (t > 9999) break;if (isFourDight(t)) polyNumbers["square"].push_back(t);}for (int n = 1; ; ++n) {int t = pentagon(n);if (t > 9999) break;if (isFourDight(t)) polyNumbers["pentagon"].push_back(t);}for (int n = 1; ; ++n) {int t = hexagon(n);if (t > 9999) break;if (isFourDight(t)) polyNumbers["hexagon"].push_back(t);}for (int n = 1; ; ++n) {int t = heptagon(n);if (t > 9999) break;if (isFourDight(t)) polyNumbers["heptagon"].push_back(t);}for (int n = 1; ; ++n) {int t = octagon(n);if (t > 9999) break;if (isFourDight(t)) polyNumbers["octagon"].push_back(t);}vector<string> types = {"triangle", "square", "pentagon", "hexagon", "heptagon", "octagon"};sort(types.begin(), types.end());do {vector<vi> polySets;for (string &type : types) {polySets.push_back(polyNumbers[type]);}for (int start : polySets[0]) {vector<int> path = {start};vector<bool> used(6, false);used[0] = true;if (dfs(polySets, path, used, 1)) {int sum = 0;for (int num : path) {cout << num << " ";sum += num;}cout << "\n";cout << sum << "\n";return ;}}} while (next_permutation(types.begin(), types.end()));}int main() {ios::sync_with_stdio(false);cin.tie(nullptr);int tt = 1; // cin >> tt;while (tt--) {solve();}return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词