欧拉计划 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;
}