backtracking

Intrebari despre limbajul C++, standardul C++, STL, OOP in C++ sau alte subiecte nelegate de VisualC++
Post Reply
david_stelian
Junior
Junior
Posts: 20
Joined: 13 Sep 2014, 22:35
Judet: Dolj

backtracking

Post by david_stelian » 19 Mar 2015, 22:41

Generare permutari.
Nu inteleg de ce nu functioneaza.
Ma puteti ajuta ?

Code: Select all

#include <iostream>
using namespace std;
int ok(int);
void afis();
void back(int);

int n, A[10], sol[10];

int main()
{
    cout << "\n Introduceti n = ";
    cin >> n;
    for (int i=1; i<=n; i++)
    {
        cout << "\n A[" << i << "] = ";
        cin >> A[i];
    }
    back(1);
    return 0;
}

void back(int k)
{
    if (k>n)
        afis();
    else
    {
        for (int i=1; i<=n; i++)
        {
            sol[k]=i;
            if (ok(k))
                back(k+1);
        }
    }
}

void afis()
{
    for (int i=1; i<=n; i++)
        cout << " " << A[sol[i]];
    cout << endl;
}

int ok(int k)
{
    for (int i=1; i<k; i++)
        if (sol[k]==sol[i])
            return 0;
        else
            return 1;
}



Viorel
Microsoft MVP
Microsoft MVP
Posts: 293
Joined: 13 Jul 2007, 12:26

Re: backtracking

Post by Viorel » 19 Mar 2015, 22:59

Cred că ultimul cuvînt else ar trebui șters.

Post Reply