AKB Forums

Go Back   AKB Forums > Technical sections > Algorithms
Home Register Blogs FAQ Members List Calendar Downloads Arcade Mark Forums Read

Algorithms The source of algorithms for your project

Troubles when posting message? Click here! :: Проблемы с отправлением сообщения? Нажмите сюда!

Reply
 
LinkBack Thread Tools Display Modes
Old May 13, 2002, 12:51   #1
Дошкольник
 
Dark Abyss of Yerevan's Avatar
 
Join Date: Jan 2002
Location: hell
Posts: 124
Rep Power: 7
Reputation: 10
Send a message via ICQ to Dark Abyss of Yerevan
Post Генерация сочетаний из n цифр по m.

Я тут написал небольшую прогу которая последовательно выводит все сочетания
из n цифр по m. Алгоритм работает как счетчик, т.е. крутит последнее число,
потом предпоследнее итд, при этом делает кое какие проверки. Вообщем:

Code:
/*		Генерация сочетаний из n цифр по m.
		abyss 11:54 AM 5/12/02
*/

#include <stdio.h>

const n=12;
const m=5;

void main(){

    int i,j;
    int v[m+1];				// we want to use v[1]..v[m]
    bool b;					// so declare it as v[m+1]
    int count=0;


    for(i=1;i<=m;i++)v[i]=i;			// initialization

    do {

	    for (;v[m]<=n;v[m]++){		// increment the last element
		    for (j=1;j<=m;j++)printf(&quot;%d &quot;,v[j]);
		    printf(&quot;\n&quot;);
		    count++;
	    }
				
	    /*	the last element has reached the right boundary, so make
		arrangements and continue	*/
	    b=false;
	    for (i=m-1;i>0;i--)
	    	    if(b=v[i]+1<=n-(m-i)) break;
	    v[i]++;
		
	    /* v[i] incremented, now arrange elements v[j],j>i   */
	    for (j=i+1;j<=m;j++)v[j]=v[j-1]+1;

    } while (b);


    printf (&quot;Count=%d\n&quot;,count);

}
Я знаю что эта задача имеет одно очень красивое решение. Кому не лень пусть
напишет свою версию, потом сравним, оценим сложности алгоритмов итд.
__________________
[x]-=-[ ]-=-[x]
Dark Abyss of Yerevan is offline   Reply With Quote Quote selected
Old May 13, 2002, 13:59   #2
The Reloaded
 
Aram Hambardzumyan's Avatar
 
Join Date: Jan 2002
Location: behind the flesh and gelatinе of soft dull eyes
Posts: 3,166
Rep Power: 7
Reputation: 34
Post

Quote:
Originally posted by Dark Abyss of Yerevan:
Я знаю что эта задача имеет одно очень красивое решение.
а я знаю, что стандартная библиотека c++ содержит функцию next_permutation, которая и выполняет это все
Aram Hambardzumyan is offline   Reply With Quote Quote selected
Old May 13, 2002, 15:01   #3
Игроман Заядлый - 1шт. ;)
 
-=iR0Nr@T=-'s Avatar
 
Join Date: Mar 2002
Location: Armenia
Posts: 303
Rep Power: 7
Reputation: 10
Send a message via ICQ to -=iR0Nr@T=-
Post

i mojet vsetaki schetchiki nachnesh` s nulya kak prinyato v C/C++????

Eto nasledie ot paskalya???
-=iR0Nr@T=- is offline   Reply With Quote Quote selected
Old May 14, 2002, 04:43   #4
Младенец
 
Join Date: May 2002
Location: Yerevan
Posts: 5
Rep Power: 0
Reputation: 10
Post

Code:
  
#include <iostream>
#include <vector>
using namespace std;

void print(const vector<int>& a)
{
	for (unsigned i = 0; i< a.size(); i++)
	{
		cout << a[i] << ' ';
	}
	cout << endl;
}

void perm(vector<int>& a, int n, int m, int first, int ind)
{
	if (ind > m)
	{
		print (a);
		return;
	}
	for (int i = first; i <= n - (m - ind); i++)
	{
		a[ind - 1] = i;
		perm (a, n, m, i + 1, ind + 1);
	}
}

void print_perm (int n, int m)
{
	vector<int> a;
	a.resize (m);
	perm(a, n, m, 1, 1);
}

int main()
{
	print_perm(12, 5);
	return 0;
}
Например так, но лучше всего использовать STL. Что касается сложности, то по порядку оба решения эквивалентны.
Grigor is offline   Reply With Quote Quote selected
Old May 18, 2002, 19:09   #5
The Reloaded
 
Aram Hambardzumyan's Avatar
 
Join Date: Jan 2002
Location: behind the flesh and gelatinе of soft dull eyes
Posts: 3,166
Rep Power: 7
Reputation: 34
Post

Quote:
Originally posted by Aram Hambardzumyan:
Quote:
Originally posted by Dark Abyss of Yerevan:
Я знаю что эта задача имеет одно очень красивое решение.
а я знаю, что стандартная библиотека c++ содержит функцию next_permutation, которая и выполняет это все
пардон, я напутал, эта функция генерирует перестановки...
Aram Hambardzumyan is offline   Reply With Quote Quote selected
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT. The time now is 01:44.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
This board was founded on September 29, 2001
Powered by Viper Internet

Affordable Web Hosting | ParevNet

Buy text link