Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6.  
  7. class Task {
  8. public:
  9. void solve() {
  10. read_input();
  11. print_output(get_result());
  12. }
  13.  
  14. private:
  15. int n;
  16. vector<int> mysol;
  17. void read_input() {
  18. ifstream fin("in");
  19. fin >> n;
  20. fin.close();
  21. }
  22. int myabs(int x) {
  23. if(x < 0) {
  24. return -x;
  25. }
  26. return x;
  27. }
  28.  
  29. int check(std::vector<int> sol, int k) {
  30. for(int i = 1; i < k; i++) {
  31. if(sol[k] == sol[i]) {
  32. return 0;
  33. }
  34. if((k - i) == myabs(sol[k] - sol[i])) {
  35. return 0;
  36. }
  37. }
  38. return 1;
  39. }
  40.  
  41. void bkt(std::vector<int> &sol, int k, int &ok) {
  42. if(k == n + 1) {
  43. if(ok == 0) {
  44. mysol = sol;
  45. ok = 1;
  46. }
  47. } else {
  48. for(int i = 1; i <= n; i++) {
  49. sol[k] = i;
  50. if(check(sol, k) == 1) {
  51. bkt(sol, k + 1, ok);
  52. }
  53. }
  54. }
  55. }
  56.  
  57. vector<int> get_result() {
  58. vector<int> sol(n + 1, 0);
  59. mysol.resize(n + 1);
  60. int ok = 0;
  61. bkt(sol, 1, ok);
  62.  
  63. /*
  64. TODO: Gasiti o solutie pentru problema damelor pe o tabla de dimensiune
  65. n x n.
  66.  
  67. Pentru a plasa o dama pe randul i, coloana j:
  68. sol[i] = j.
  69. Randurile si coloanele se indexeaza de la 1 la n.
  70.  
  71. De exemplu, configuratia (n = 5)
  72. X----
  73. --X--
  74. ----X
  75. -X---
  76. ---X-
  77. se va reprezenta prin sol[1..5] = {1, 3, 5, 2, 4}.
  78. */
  79.  
  80. return mysol;
  81. }
  82.  
  83. void print_output(vector<int> result) {
  84. ofstream fout("out");
  85. for (int i = 1; i <= n; i++) {
  86. fout << result[i] << (i != n ? ' ' : '\n');
  87. }
  88. fout.close();
  89. }
  90. };
  91.  
  92. int main() {
  93. Task task;
  94. task.solve();
  95. return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement