<?xml version='1.0' encoding="utf-8"?>
      <rss version='2.0'>
      <channel>
      <title>Форум на Исходниках.RU</title>
      <link>https://forum.sources.ru</link>
      <description>Форум на Исходниках.RU</description>
      <generator>Форум на Исходниках.RU</generator>
  	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=2518839</guid>
        <pubDate>Sun, 28 Feb 2010 20:43:57 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=2518839</link>
        <description><![CDATA[cooller01: Всем привет&#33;<br>Ребят, может подскажете мне.... давненько я уже прог не писал, но тут понадобилось...<br>мне нужно написать на С++ в Билдере:<br>1) рекурентный способ вывода списка перестановок из n-элементов в лексикографическом порядке;<br>2) нерекурентный- вводим лексикографический номер, разряд перестановки и исходное множество, нам в ответ- перестановку;<br>3) нерекурентный- наоборот: вводим перестановку а машина нам даёт её лексикографический номер.<br><br>вот програмка котурую тут обсуждали...я не очень понял что она реализует. Её вроде можно использовать в одном пункте]]></description>
        <author>cooller01</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=1578743</guid>
        <pubDate>Fri, 25 May 2007 10:13:23 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=1578743</link>
        <description><![CDATA[SVK: по просьбе трудящихся  8-) дублирую код из предыдущего сообщения..<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">#include &#60;fstream&#62;</div><div class="code_line">#include &#60;iostream&#62;</div><div class="code_line">#include &#60;string&#62;</div><div class="code_line">#include &#60;algorithm&#62;</div><div class="code_line">#include &#60;iomanip&#62;</div><div class="code_line">&nbsp;</div><div class="code_line">using namespace std;</div><div class="code_line">&nbsp;</div><div class="code_line">// global variables</div><div class="code_line">unsigned long &nbsp;counter = 0;</div><div class="code_line">bool fl &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; = false;</div><div class="code_line">string StrToFind;</div><div class="code_line">&nbsp;</div><div class="code_line">// function defenitions</div><div class="code_line">ostream &amp; operator &#60;&#60; (ofstream &amp;str,string &amp;s);</div><div class="code_line">istream &amp; operator &#62;&#62; (ifstream &amp;str,string &amp;s);</div><div class="code_line">void GivePermNum(string a,string b);</div><div class="code_line">int main();</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">int main()</div><div class="code_line">{</div><div class="code_line">string s;</div><div class="code_line">&nbsp;</div><div class="code_line">while(true)</div><div class="code_line">{</div><div class="code_line">cin&#62;&#62;StrToFind;</div><div class="code_line">if((string)&quot;#&quot; == StrToFind) break;</div><div class="code_line">else</div><div class="code_line">{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;s = StrToFind;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;sort(s.begin(),s.end());</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;fl = true;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;counter = 0;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;GivePermNum(s,(string)&quot;&quot;);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;cout.setf(ios::right);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;cout&#60;&#60;setw(10)&#60;&#60;(counter + 1)&#60;&#60;endl;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">return 0;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">void GivePermNum(string a,string b)</div><div class="code_line">{</div><div class="code_line">char last = 0;</div><div class="code_line">int &nbsp;i &nbsp; &nbsp; &nbsp; &nbsp;= 0;</div><div class="code_line">string s;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;if(0 == a.length())</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(StrToFind == b)</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fl = false;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;counter++;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;else</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;int iLen = a.length();</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for(i = 0; i &#60; iLen &amp;&amp; fl; i++)</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (last != a[i])</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;last = a[i];</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s &nbsp; &nbsp; &nbsp; = a;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s.erase(s.begin() + i);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;GivePermNum(s,b + last);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;}</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">ostream &amp; operator &#60;&#60; (ofstream &amp;str,string &amp;s)</div><div class="code_line">{</div><div class="code_line">int i, iLen = s.length();</div><div class="code_line">for(i = 0; i &#60; iLen; str&#60;&#60;s[i++]);</div><div class="code_line">return str;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">istream &amp; operator &#62;&#62; (ifstream &amp;str,string &amp;s)</div><div class="code_line">{</div><div class="code_line">char c; bool fl = true;</div><div class="code_line">while(fl)</div><div class="code_line">{</div><div class="code_line">cin&#62;&#62;c;</div><div class="code_line">if(c==&#39;\n&#39;) fl = false;</div><div class="code_line">else s+=c;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">return str;</div><div class="code_line">}</div></ol></div></div></div></div><script>preloadCodeButtons('1');</script>из сообщения №22<div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">#include &#60;fstream&#62;</div><div class="code_line">#include &#60;iostream&#62;</div><div class="code_line">#include &#60;string&#62;</div><div class="code_line">#include &#60;algorithm&#62;</div><div class="code_line">#include &#60;iomanip&#62;</div><div class="code_line">&nbsp;</div><div class="code_line">using namespace std;</div><div class="code_line">&nbsp;</div><div class="code_line">// global variables</div><div class="code_line">long double counter = 0;</div><div class="code_line">bool fl &nbsp; &nbsp; &nbsp;= false;</div><div class="code_line">string StrToFind;</div><div class="code_line">string StrDistinct;</div><div class="code_line">&nbsp;</div><div class="code_line">// function defenitions</div><div class="code_line">ostream &amp; operator &#60;&#60; (ofstream &amp;str,string &amp;s);</div><div class="code_line">istream &amp; operator &#62;&#62; (ifstream &amp;str,string &amp;s);</div><div class="code_line">&nbsp;</div><div class="code_line">long double GivePermNum &nbsp; (string a,string b);</div><div class="code_line">long double GiveFactorial (string a);</div><div class="code_line">long double Factorial &nbsp; &nbsp; (long double n);</div><div class="code_line">void &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;MakeDistinct(string &amp;s);</div><div class="code_line">&nbsp;</div><div class="code_line">int main();</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">int main()</div><div class="code_line">{</div><div class="code_line">string s;</div><div class="code_line">long double &nbsp;lC;</div><div class="code_line">cout.setf(ios::right);</div><div class="code_line">&nbsp;</div><div class="code_line">while(true)</div><div class="code_line">{</div><div class="code_line">cin&#62;&#62;StrToFind;</div><div class="code_line">if((string)&quot;#&quot; == StrToFind) break;</div><div class="code_line">else</div><div class="code_line">{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;s = StrToFind;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;StrDistinct = StrToFind;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;sort(StrDistinct.begin(),StrDistinct.end());</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;sort(s.begin(),s.end());</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;MakeDistinct(StrDistinct);</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;lC = GivePermNum(s,StrToFind);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;cout&#60;&#60;setw(10)&#60;&#60;(long int)(lC + 0.5)&#60;&#60;endl;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">return 0;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">long double GivePermNum(string a,string b)</div><div class="code_line">{</div><div class="code_line">&nbsp;</div><div class="code_line">if((size_t)1 == a.length()) return (long double )1;</div><div class="code_line">if(a == b ) return (long double )1;</div><div class="code_line">&nbsp;</div><div class="code_line">int i = 0,j = 0;</div><div class="code_line">long double lCounter = 0;</div><div class="code_line">string c;</div><div class="code_line">&nbsp;</div><div class="code_line">while(StrDistinct[i] !=a[0]) i++;</div><div class="code_line">&nbsp;</div><div class="code_line">while(StrDistinct[i] &#60; b[0])</div><div class="code_line">{</div><div class="code_line">j = 0;</div><div class="code_line">c = a;</div><div class="code_line">while(c[j]!= StrDistinct[i]) j++;</div><div class="code_line">c.erase(c.begin() + j);</div><div class="code_line">lCounter += GiveFactorial(c);</div><div class="code_line">i++;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">bool fl = false;</div><div class="code_line">&nbsp;</div><div class="code_line">i = 0;</div><div class="code_line">while(a[i]!= b[0]) i++;</div><div class="code_line">a.erase(a.begin() + i);</div><div class="code_line">sort(a.begin(),a.end());</div><div class="code_line">&nbsp;</div><div class="code_line">for(i = 0; i &#60; a.length() &amp;&amp; !fl; i++)</div><div class="code_line">{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;if(a[i] == b[0]) fl = true;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">if(!fl)</div><div class="code_line">{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;i = 0;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;while(StrDistinct[i] !=b[0]) i++;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;StrDistinct.erase(StrDistinct.begin() + i);</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;</div><div class="code_line">return lCounter + GivePermNum(a,b.substr(1,b.length() -1));</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">long double GiveFactorial(string a)</div><div class="code_line">{</div><div class="code_line">int i = 0, iLen = a.length();</div><div class="code_line">long double &nbsp;lResult = Factorial(iLen);</div><div class="code_line">long double &nbsp;lRepeats;</div><div class="code_line">char last;</div><div class="code_line">&nbsp;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;for(i = 0,lRepeats = 0,last = a[0]; i &#60; iLen; i++)</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(last == a[i]) lRepeats++;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;last = a[i];</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;lResult/=Factorial(lRepeats);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;lRepeats = 1;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;}</div><div class="code_line">&nbsp;</div><div class="code_line">lResult/=Factorial(lRepeats);</div><div class="code_line">return lResult;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">long double Factorial(long double n)</div><div class="code_line">{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;return (0 == n) ? (long double)1 : n*Factorial(n-1);</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">void MakeDistinct(string &amp;s)</div><div class="code_line">{</div><div class="code_line">int i = 1;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;while(i &#60; s.length())</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;{</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(s[i] == s[i-1])</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s.erase(s.begin() + i);</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else i++;</div><div class="code_line">&nbsp;&nbsp; &nbsp; &nbsp;}</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">ostream &amp; operator &#60;&#60; (ofstream &amp;str,string &amp;s)</div><div class="code_line">{</div><div class="code_line">int i, iLen = s.length();</div><div class="code_line">for(i = 0; i &#60; iLen; str&#60;&#60;s[i++]);</div><div class="code_line">return str;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">istream &amp; operator &#62;&#62; (ifstream &amp;str,string &amp;s)</div><div class="code_line">{</div><div class="code_line">char c; bool fl = true;</div><div class="code_line">while(fl)</div><div class="code_line">{</div><div class="code_line">cin&#62;&#62;c;</div><div class="code_line">if(c==&#39;\n&#39;) fl = false;</div><div class="code_line">else s+=c;</div><div class="code_line">}</div><div class="code_line">&nbsp;</div><div class="code_line">return str;</div><div class="code_line">}</div></ol></div></div></div></div>]]></description>
        <author>SVK</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90692</guid>
        <pubDate>Mon, 07 Jul 2003 11:28:43 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90692</link>
        <description><![CDATA[experimenter: вот ссылка. http://acm.uva.es/problemset/submit.php<br>номер задачи 153, а ID надо получить,т.е. зарегиться.<br>насчет алгоритма. я имел ввиду, что если делать, как я изначально предполагал, т.е. генерить все подряд в лексографическом порядке, пока не встретишь нужную, то это занимает очень много времени. а на счет обратимости я не знаю, скорее всего да, но это по-моему смысла не имеет.<br>вот код такой программы: считает все &quot;на ура&quot;, но долго, правда надо, наверное, long int на long double заменить.<br><br><div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">&#60;br&#62;#include &#60;fstream&#62;&#60;br&#62;#include &#60;iostream&#62;&#60;br&#62;#include &#60;string&#62;&#60;br&#62;#include &#60;algorithm&#62;&#60;br&#62;#include &#60;iomanip&#62;&#60;br&#62;&#60;br&#62;using namespace std;&#60;br&#62;&#60;br&#62;// global variables&#60;br&#62;unsigned long  counter = 0;&#60;br&#62;bool fl             = false;&#60;br&#62;string StrToFind;&#60;br&#62;&#60;br&#62;// function defenitions&#60;br&#62;ostream &amp; operator &#60;&#60; (ofstream &amp;str,string &amp;s);&#60;br&#62;istream &amp; operator &#62;&#62; (ifstream &amp;str,string &amp;s);&#60;br&#62;void GivePermNum(string a,string b);&#60;br&#62;int main();&#60;br&#62;&#60;br&#62;&#60;br&#62;int main()&#60;br&#62;{&#60;br&#62;string s;&#60;br&#62;&#60;br&#62;while(true)&#60;br&#62;{&#60;br&#62;cin&#62;&#62;StrToFind;&#60;br&#62;if((string)&quot;#&quot; == StrToFind) break;&#60;br&#62;else&#60;br&#62;{&#60;br&#62;      s = StrToFind;&#60;br&#62;      sort(s.begin(),s.end());&#60;br&#62;&#60;br&#62;      fl = true;&#60;br&#62;      counter = 0;&#60;br&#62;      GivePermNum(s,(string)&quot;&quot;);&#60;br&#62;      cout.setf(ios::right);&#60;br&#62;      cout&#60;&#60;setw(10)&#60;&#60;(counter + 1)&#60;&#60;endl;&#60;br&#62;}&#60;br&#62;&#60;br&#62;}&#60;br&#62;&#60;br&#62;return 0;&#60;br&#62;}&#60;br&#62;&#60;br&#62;void GivePermNum(string a,string b)&#60;br&#62;{&#60;br&#62;char last = 0;&#60;br&#62;int  i        = 0;&#60;br&#62;string s;&#60;br&#62;&#60;br&#62;      if(0 == a.length())      &#60;br&#62;      {&#60;br&#62;            if(StrToFind == b)&#60;br&#62;                  fl = false;&#60;br&#62;            else&#60;br&#62;                  counter++;&#60;br&#62;&#60;br&#62;            return;&#60;br&#62;      }&#60;br&#62;&#60;br&#62;      else&#60;br&#62;      {&#60;br&#62;            int iLen = a.length();&#60;br&#62;            for(i = 0; i &#60; iLen &amp;&amp; fl; i++)&#60;br&#62;            {&#60;br&#62;                  if (last != a[i])&#60;br&#62;                  {&#60;br&#62;                        last = a[i];&#60;br&#62;                        s       = a;&#60;br&#62;                        s.erase(s.begin() + i);&#60;br&#62;                        GivePermNum(s,b + last);&#60;br&#62;                  }&#60;br&#62;&#60;br&#62;            }&#60;br&#62;      }&#60;br&#62;}&#60;br&#62;&#60;br&#62;ostream &amp; operator &#60;&#60; (ofstream &amp;str,string &amp;s)&#60;br&#62;{&#60;br&#62;int i, iLen = s.length();&#60;br&#62;for(i = 0; i &#60; iLen; str&#60;&#60;s[i++]);&#60;br&#62;return str;&#60;br&#62;}&#60;br&#62;&#60;br&#62;istream &amp; operator &#62;&#62; (ifstream &amp;str,string &amp;s)&#60;br&#62;{&#60;br&#62;char c; bool fl = true;&#60;br&#62;while(fl)&#60;br&#62;{&#60;br&#62;cin&#62;&#62;c;&#60;br&#62;if(c==&#39;\n&#39;) fl = false;&#60;br&#62;else s+=c;&#60;br&#62;}&#60;br&#62;&#60;br&#62;return str;&#60;br&#62;}&#60;br&#62;&#60;br&#62;</div></ol></div></div></div></div><br>зы<br>т.е. в итоге сопоставить взаимное соответсвие я не смог, но быстро подссчитать номер смог(в предыдущей проге, а не в той, которая в этом посте.)]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90691</guid>
        <pubDate>Mon, 07 Jul 2003 10:12:02 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90691</link>
        <description><![CDATA[SVK: <div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>Experimenter, 07.07.03, 13:45:13</span><div class='quote '>код писал сам.</div></div>Никаких притензий :)<br><br><div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>Experimenter, 07.07.03, 13:45:13</span><div class='quote '>факториал - вещь нормальная.</div></div>Я имел в виду, что при больших (даже не очень) перестановках, его значение вылезет за разрядную сетку long double.<br><br><div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>Experimenter, 07.07.03, 13:45:13</span><div class='quote '>программу, которая подсчитывает перстановками, я написал, но, чтобы получить ответ от нее, тебе придется ждать до пенсии, в то время как выше написанной потребуется сотые доли секунды.</div></div>Не совсем тебя понял, и вообще, пока ты его еще не забыл - освети подробно, но сжато и формулизировано принцип алгоритма, если не жалко. (Кстати, он обратим?)<br><br><div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>Experimenter, 07.07.03, 13:45:13</span><div class='quote '>вообще программа написана как олимпиадная задача и оттестирована роботом вот здесь http://acm.uva.es/board/index.php</div></div>Какая то 'размытая' ссылка, нельзяль по подробнее.<br><br><div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>Experimenter, 07.07.03, 13:45:13</span><div class='quote '>и потом, как тебе что-то знакомо, если ты 4 года прогу не видел, алгоритм забыл, а тут тебе показывают прогу, да еще не твою, а ты говоришь, что-де она похожа на твою, 4х-годичной давности?</div></div>У меня феноминальная память на 'лица' 8D Кстати я этого (она похожа на твою) не говорил ;)]]></description>
        <author>SVK</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90690</guid>
        <pubDate>Mon, 07 Jul 2003 09:45:13 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90690</link>
        <description><![CDATA[experimenter: <div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>SVK, 07.07.03, 10:27:15</span><div class='quote '><br>Ты совершил одну очень большую ошибку о которой я предупреждал ;) Кстати, код какой-то получился до боли знакомый 8D И советую всю математику перевести на работу со строчным представлением цифр, факториал: - вещь страшная :(<br></div></div><br>код писал сам. факториал - вещь нормальная. программу, которая подсчитывает перстановками, я написал, но, чтобы получить ответ от нее, тебе придется ждать до пенсии, в то время как выше написанной потребуется сотые доли секунды.<br>например, чтобы определить номер последней перестановки из 12 разных букв той проге придется проделать 12! = 479'001'600 итераций. чуешь? или еще нет?<br>так вот обычно проги работают терпимо при кол-ве операций около максимум 10 мил., а тут их почти 500, так что временной тест твоя идея никакой не проходит. :P<br>вообще программа написана как олимпиадная задача и оттестирована роботом вот здесь<br>http://acm.uva.es/board/index.php, так что все вопросы к нему, если тебе кажется что-то неправильно. и потом, как тебе что-то знакомо, если ты 4 года прогу не видел, алгоритм забыл, а тут тебе показывают прогу, да еще не твою, а ты говоришь, что-де она похожа на твою, 4х-годичной давности? только не говори, что ты имел ввиду, что она похожа на прогу, которую твой сосед написал или ты видел её в инете, ну, я думаю, ты понимаешь почему? ;D<br>зы<br>блин, я весь пост просмотрел и не нашел ни одного твоего предуприждения на счет какой-либо ошибки.  :P]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90689</guid>
        <pubDate>Mon, 07 Jul 2003 06:27:15 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90689</link>
        <description><![CDATA[SVK: <div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>Experimenter, 07.07.03, 09:31:28</span><div class='quote '>эту задачу я решил, наконец-то. решил без генерения.<br>идея такова. есть, например, перестановка aabc (самая первая).<br>от нее надо добраться до caba. чтобы добраться, надо сначала пройти все перестановки<br>a???, которых 3! = 6, потом<br>b???, которых 3!/2! = 3, потом<br>приходим к перестановке сaab. одну букву подобрали. <br>таким же макаром движемся от перестановки aab до aba, суммируя перестановки на каждом шаге.<br>алгоритм и программа рабочие. работает очень быстро.<br><br>вот код на С++</div></div>Ты совершил одну очень большую ошибку о которой я предупреждал ;) Кстати, код какой-то получился до боли знакомый 8D И советую всю математику перевести на работу со строчным представлением цифр, факториал: - вещь страшная :(<br>]]></description>
        <author>SVK</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90688</guid>
        <pubDate>Mon, 07 Jul 2003 05:31:28 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90688</link>
        <description><![CDATA[experimenter: эту задачу я решил, наконец-то. решил без генерения.<br>идея такова. есть, например, перестановка aabc (самая первая).<br>от нее надо добраться до caba. чтобы добраться, надо сначала пройти все перестановки<br>a???, которых 3! = 6, потом<br>b???, которых 3!/2! = 3, потом<br>приходим к перестановке сaab. одну букву подобрали. <br>таким же макаром движемся от перестановки aab до aba, суммируя перестановки на каждом шаге.<br>алгоритм и программа рабочие. работает очень быстро.<br><br>вот код на С++.<br><div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">&#60;br&#62;#include &#60;fstream&#62;&#60;br&#62;#include &#60;iostream&#62;&#60;br&#62;#include &#60;string&#62;&#60;br&#62;#include &#60;algorithm&#62;&#60;br&#62;#include &#60;iomanip&#62;&#60;br&#62;&#60;br&#62;using namespace std;&#60;br&#62;&#60;br&#62;// global variables&#60;br&#62;long double counter = 0;&#60;br&#62;bool fl      = false;&#60;br&#62;string StrToFind;&#60;br&#62;string StrDistinct;&#60;br&#62;&#60;br&#62;// function defenitions&#60;br&#62;ostream &amp; operator &#60;&#60; (ofstream &amp;str,string &amp;s);&#60;br&#62;istream &amp; operator &#62;&#62; (ifstream &amp;str,string &amp;s);&#60;br&#62;&#60;br&#62;long double GivePermNum   (string a,string b);&#60;br&#62;long double GiveFactorial (string a);&#60;br&#62;long double Factorial     (long double n);&#60;br&#62;void              MakeDistinct(string &amp;s); &#60;br&#62;&#60;br&#62;int main();&#60;br&#62;&#60;br&#62;&#60;br&#62;int main()&#60;br&#62;{&#60;br&#62;string s;&#60;br&#62;long double  lC;&#60;br&#62;cout.setf(ios::right);&#60;br&#62;&#60;br&#62;while(true)&#60;br&#62;{&#60;br&#62;cin&#62;&#62;StrToFind;&#60;br&#62;if((string)&quot;#&quot; == StrToFind) break;&#60;br&#62;else&#60;br&#62;{&#60;br&#62;      s = StrToFind;&#60;br&#62;      StrDistinct = StrToFind;&#60;br&#62;      sort(StrDistinct.begin(),StrDistinct.end());&#60;br&#62;      sort(s.begin(),s.end());&#60;br&#62;      MakeDistinct(StrDistinct);&#60;br&#62;&#60;br&#62;      lC = GivePermNum(s,StrToFind);&#60;br&#62;      cout&#60;&#60;setw(10)&#60;&#60;(long int)(lC + 0.5)&#60;&#60;endl;&#60;br&#62;}&#60;br&#62;&#60;br&#62;}&#60;br&#62;&#60;br&#62;return 0;&#60;br&#62;}&#60;br&#62;&#60;br&#62;long double GivePermNum(string a,string b)&#60;br&#62;{&#60;br&#62;&#60;br&#62;if((size_t)1 == a.length()) return (long double )1;&#60;br&#62;if(a == b ) return (long double )1;&#60;br&#62;&#60;br&#62;int i = 0,j = 0;&#60;br&#62;long double lCounter = 0;&#60;br&#62;string c;&#60;br&#62;&#60;br&#62;while(StrDistinct[i] !=a[0]) i++;&#60;br&#62;&#60;br&#62;while(StrDistinct[i] &#60; b[0])&#60;br&#62;{&#60;br&#62;j = 0;&#60;br&#62;c = a;&#60;br&#62;while(c[j]!= StrDistinct[i]) j++;&#60;br&#62;c.erase(c.begin() + j);&#60;br&#62;lCounter += GiveFactorial(c);&#60;br&#62;i++;&#60;br&#62;}&#60;br&#62;&#60;br&#62;bool fl = false;&#60;br&#62;&#60;br&#62;i = 0;&#60;br&#62;while(a[i]!= b[0]) i++;&#60;br&#62;a.erase(a.begin() + i);&#60;br&#62;sort(a.begin(),a.end());&#60;br&#62;&#60;br&#62;for(i = 0; i &#60; a.length() &amp;&amp; !fl; i++)&#60;br&#62;{&#60;br&#62;      if(a[i] == b[0]) fl = true;&#60;br&#62;}&#60;br&#62;&#60;br&#62;if(!fl)&#60;br&#62;{&#60;br&#62;      i = 0;&#60;br&#62;      while(StrDistinct[i] !=b[0]) i++;&#60;br&#62;      StrDistinct.erase(StrDistinct.begin() + i);&#60;br&#62;}&#60;br&#62;&#60;br&#62;&#60;br&#62;return lCounter + GivePermNum(a,b.substr(1,b.length() -1));&#60;br&#62;}&#60;br&#62;&#60;br&#62;long double GiveFactorial(string a)&#60;br&#62;{&#60;br&#62;int i = 0, iLen = a.length();&#60;br&#62;long double  lResult = Factorial(iLen);&#60;br&#62;long double  lRepeats;&#60;br&#62;char last;&#60;br&#62;&#60;br&#62;      for(i = 0,lRepeats = 0,last = a[0]; i &#60; iLen; i++)&#60;br&#62;      {&#60;br&#62;            if(last == a[i]) lRepeats++;&#60;br&#62;            else&#60;br&#62;            { &#60;br&#62;                  last = a[i];&#60;br&#62;                  lResult/=Factorial(lRepeats);&#60;br&#62;                  lRepeats = 1;&#60;br&#62;            }&#60;br&#62;      }&#60;br&#62;      &#60;br&#62;lResult/=Factorial(lRepeats);&#60;br&#62;return lResult;&#60;br&#62;}&#60;br&#62;&#60;br&#62;long double Factorial(long double n)&#60;br&#62;{&#60;br&#62;      return (0 == n) ? (long double)1 : n*Factorial(n-1);&#60;br&#62;}&#60;br&#62;&#60;br&#62;void MakeDistinct(string &amp;s)&#60;br&#62;{&#60;br&#62;int i = 1;&#60;br&#62;      while(i &#60; s.length())&#60;br&#62;      {&#60;br&#62;            if(s[i] == s[i-1])&#60;br&#62;                  s.erase(s.begin() + i);&#60;br&#62;            else i++;&#60;br&#62;      }&#60;br&#62;}&#60;br&#62;&#60;br&#62;ostream &amp; operator &#60;&#60; (ofstream &amp;str,string &amp;s)&#60;br&#62;{&#60;br&#62;int i, iLen = s.length();&#60;br&#62;for(i = 0; i &#60; iLen; str&#60;&#60;s[i++]);&#60;br&#62;return str;&#60;br&#62;}&#60;br&#62;&#60;br&#62;istream &amp; operator &#62;&#62; (ifstream &amp;str,string &amp;s)&#60;br&#62;{&#60;br&#62;char c; bool fl = true;&#60;br&#62;while(fl)&#60;br&#62;{&#60;br&#62;cin&#62;&#62;c;&#60;br&#62;if(c==&#39;\n&#39;) fl = false;&#60;br&#62;else s+=c;&#60;br&#62;}&#60;br&#62;&#60;br&#62;return str;&#60;br&#62;}&#60;br&#62;</div></ol></div></div></div></div>]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90687</guid>
        <pubDate>Mon, 23 Jun 2003 06:01:58 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90687</link>
        <description><![CDATA[SVK : <div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>Experimenter, 21.06.03, 18:59:34</span><div class='quote '>ну, ты бы хоть примерный алгоритм сказал. :-/</div></div>Дк.. этот код был написан четыре года назад и алгоритм, который я выдумывал сам, уже давно забыт :(<br>Так что, Господа Программисты, никогда не ленитесь писать комментарии ;)<br>Если есть желание, то могу выслать полный проект той прожки в которой использовался этот код, хотя кому-то я ее уже когда-то &nbsp;высылал...<br>]]></description>
        <author>SVK </author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90686</guid>
        <pubDate>Sat, 21 Jun 2003 14:59:34 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90686</link>
        <description><![CDATA[experimenter: ну, ты бы хоть примерный алгоритм сказал. :-/]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90685</guid>
        <pubDate>Sat, 21 Jun 2003 14:43:31 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90685</link>
        <description><![CDATA[SVK : Я так понимаю, что до кода дело так и не дошло, тады вот: (хотел еще неделю назад публикануть, но посмотрел и понял как все запущено; однако может ктоньть разберется)<br><div class='tag-code'><span class='pre_code'></span><div class='code  code_collapsed ' title='Подсветка синтаксиса доступна зарегистрированным участникам Форума.' style=''><div><div><ol type="1"><div class="code_line">&#60;br&#62;char GenKey( &nbsp;HWND &nbsp;hwndDlg,&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char lkey,//длинна перестановки&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char * keymask,//какойто выходной буфер :)&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char _sys_=0,//признак цикличного вызова&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char * numkey=0,//перестановка на выходе цикличного вызова&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; char *start=0//номер перестановки цикличного вызова&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;)&#60;br&#62; {&#60;br&#62; &nbsp;static char i,k,mask[3],nu[MaxLenMath+1],nur[MaxLenMath+1],fa[MaxLenMath+1],f;&#60;br&#62;&#60;br&#62; &nbsp;if(!_sys_)SendDlgItemMessage(hwndDlg,IDC_EDIT31,WM_GETTEXT,&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (WPARAM)(MaxLenMath+1),(LPARAM)nur);&#60;br&#62; &nbsp;if(_sys_){strcpy(nur,start);nu[0]=&#39;1&#39;;nu[1]=0;add(start,nu);}&#60;br&#62;&#60;br&#62; &nbsp;for(i=0;i&#60;lkey;i++){keymask[i]=0;}&#60;br&#62; &nbsp;fak(fa,lkey);&#60;br&#62;&#60;br&#62; &nbsp;f=0;&#60;br&#62; &nbsp;if(strlen(nur)&#62;strlen(fa)+1){nur[strlen(fa)+1]=0;f=1;}&#60;br&#62; &nbsp;while(sub(nur,fa)) f++;&#60;br&#62;&#60;br&#62; &nbsp;for(i=lkey;i&#62;1;i--)&#60;br&#62; &nbsp; {&#60;br&#62; &nbsp; &nbsp;strcpy(nu,nur);&#60;br&#62; &nbsp; &nbsp;while(sub(nu,fa));k=0;&#60;br&#62; &nbsp; &nbsp;strcpy(nur,nu);&#60;br&#62; &nbsp; &nbsp;fak(fa,i-1);&#60;br&#62; &nbsp; &nbsp;while(sub(nu,fa)) k++;&#60;br&#62; &nbsp; &nbsp;k=k+1+(lkey-i);&#60;br&#62; &nbsp; &nbsp;while(keymask[k-1])k=keymask[k-1];&#60;br&#62; &nbsp; &nbsp;keymask[k-1]=lkey-i+1;&#60;br&#62; &nbsp; &nbsp;if(!_sys_){sprintf(mask,&quot;\%d&quot;,k);&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SendDlgItemMessage(hwndDlg,IDC_EDIT1+lkey-i,WM_SETTEXT,0,&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(LPARAM)mask);&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} else numkey[lkey-i+1]=k;&#60;br&#62; &nbsp; }&#60;br&#62; &nbsp;k=lkey;&#60;br&#62; &nbsp;while(keymask[k-1])k=keymask[k-1];&#60;br&#62; &nbsp;if(!_sys_){sprintf(mask,&quot;\%d&quot;,k);&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SendDlgItemMessage(hwndDlg,IDC_EDIT0+lkey,WM_SETTEXT,0,&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(LPARAM)mask);&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} else numkey[lkey]=k;&#60;br&#62; &nbsp;return f;&#60;br&#62; }&#60;br&#62;&#60;br&#62;void ReGenKey(HWND &nbsp;hwndDlg,char lkey,char * keymask)&#60;br&#62; {&#60;br&#62; &nbsp;char i,k,p,mask[3],nu[MaxLenMath+1]=&quot;0&quot;,fa[MaxLenMath+1];&#60;br&#62;&#60;br&#62; &nbsp;for(i=0;i&#60;lkey;i++){keymask[i]=0;}&#60;br&#62; &nbsp;for(i=0;i&#60;(lkey-1);i++)&#60;br&#62; &nbsp; {&#60;br&#62; &nbsp; &nbsp;SendDlgItemMessage(hwndDlg,IDC_EDIT1+i,WM_GETTEXT,(WPARAM)3,(LPARAM)mask);&#60;br&#62; &nbsp; &nbsp;k=MyAtoi(mask);&#60;br&#62; &nbsp; &nbsp;while(keymask[k-1])k=keymask[k-1];&#60;br&#62; &nbsp; &nbsp;keymask[i]=k;&#60;br&#62; &nbsp; &nbsp;sprintf(mask,&quot;\%d&quot;,k);&#60;br&#62; &nbsp; &nbsp;fak(fa,lkey-1-i);&#60;br&#62; &nbsp; &nbsp;p=k-(i+1);&#60;br&#62; &nbsp; &nbsp;while(p){add(nu,fa);p--;}&#60;br&#62; &nbsp; }&#60;br&#62; &nbsp;SendDlgItemMessage(hwndDlg,IDC_EDIT31,WM_SETTEXT,0,(LPARAM)nu);&#60;br&#62; }&#60;br&#62;&#60;br&#62;void trstr(char*a)&#60;br&#62; {&#60;br&#62; &nbsp;int i=0;&#60;br&#62; &nbsp;while(a[i]==&#39;0&#39;)i++;&#60;br&#62; &nbsp;if(i)strcpy(a,a+i);&#60;br&#62; }&#60;br&#62;&#60;br&#62;char sub(char * a,char * b)&#60;br&#62; {&#60;br&#62; &nbsp;char reza[MaxLenMath+1];&#60;br&#62; &nbsp;strcpy(reza,a);&#60;br&#62; &nbsp;int la=strlen(a),lb=strlen(b),i,ii;&#60;br&#62; &nbsp;for(i=lb;i&#62;0;i--)&#60;br&#62; &nbsp;{&#60;br&#62; &nbsp; if(a[la-lb-1+i]&#62;=b[i-1]) a[la-lb-1+i]=a[la-lb-1+i]-b[i-1]+&#39;0&#39;;&#60;br&#62; &nbsp; &nbsp;else{ii=i-1;&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; while(a[la-lb-1+ii]==&#39;0&#39;&amp;&amp;(la-lb-1+ii)&#62;=0) {a[la-lb-1+ii]=&#39;9&#39;;ii--;}&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; if((la-lb-1+ii)&#60;0){strcpy(a,reza);return 0;}&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; a[la-lb-1+ii]--;&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; a[la-lb-1+i]=a[la-lb-1+i]-b[i-1]+10+&#39;0&#39;;&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp;}&#60;br&#62; &nbsp;}&#60;br&#62; &nbsp;trstr(a);&#60;br&#62; &nbsp;return 1;&#60;br&#62; }&#60;br&#62;&#60;br&#62;char add(char * a,char * b)&#60;br&#62; {&#60;br&#62; &nbsp;int i=0,ii,la=strlen(a),lb=strlen(b);&#60;br&#62; &nbsp;char reza[MaxLenMath+1];&#60;br&#62; &nbsp;if(la!=MaxLenMath){for(i=0;i&#60;MaxLenMath;i++)reza[i]=&#39;0&#39;;reza[MaxLenMath]=0;&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; strcpy(reza+MaxLenMath-la,a);&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; strcpy(a,reza);&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&#60;br&#62; &nbsp;a[MaxLenMath]=0;la=MaxLenMath;&#60;br&#62; &nbsp;for(i=lb;i&#62;0;i--)&#60;br&#62; &nbsp; {&#60;br&#62; &nbsp; &nbsp;if(a[la-lb-1+i]+b[i-1]-&#39;0&#39;&#60;=&#39;9&#39;) a[la-lb-1+i]=a[la-lb-1+i]+b[i-1]-&#39;0&#39;;&#60;br&#62; &nbsp; &nbsp; else {ii=i-1;&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while(a[la-lb-1+ii]==&#39;9&#39;&amp;&amp;(la-lb-1+ii)&#62;=0){a[la-lb-1+ii]=&#39;0&#39;;ii--;}&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if((la-lb-1+ii)&#60;0)return 0;&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[la-lb-1+ii]++;&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[la-lb-1+i]=a[la-lb-1+i]+b[i-1]-10-&#39;0&#39;;&#60;br&#62; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&#60;br&#62; &nbsp; }&#60;br&#62; &nbsp;trstr(a);&#60;br&#62; &nbsp;return 1;&#60;br&#62; }&#60;br&#62;&#60;br&#62;void fak(char* a,char f)&#60;br&#62; {&#60;br&#62; &nbsp;char ff,aa[MaxLenMath+1];&#60;br&#62; &nbsp;if(f&#60;=1){a[1]=0;a[0]=&#39;1&#39;;return;}&#60;br&#62; &nbsp;sprintf(a,&quot;\%d&quot;,f);&#60;br&#62; &nbsp;strcpy(aa,a);&#60;br&#62; &nbsp;f--;&#60;br&#62; &nbsp;while(f&#62;1)&#60;br&#62; &nbsp; {&#60;br&#62; &nbsp; &nbsp;ff=f;&#60;br&#62; &nbsp; &nbsp;while(ff&#62;1){add(a,aa);ff--;}&#60;br&#62; &nbsp; &nbsp;f--;&#60;br&#62; &nbsp; &nbsp;strcpy(aa,a);&#60;br&#62; &nbsp; }&#60;br&#62; }&#60;br&#62;</div></ol></div></div></div></div>]]></description>
        <author>SVK </author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90684</guid>
        <pubDate>Thu, 19 Jun 2003 07:59:40 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90684</link>
        <description><![CDATA[experimenter: <div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>Fieral, 19.06.03, 09:45:50</span><div class='quote '>Вообще нормально бы в рекурсию уйти - мы такую задачу на уроках делали, рекурсия там будет, рекурсия. :-/</div></div><br>ну, понятно. по-моему задачи такого типа в легче всего рекурсией решать. по-крайней мере, я так всегда делаю. вопрос в другом - как организовать рекурсию. вот в чем вопрос! &nbsp;::)]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90683</guid>
        <pubDate>Thu, 19 Jun 2003 05:45:50 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90683</link>
        <description><![CDATA[Fieral: Вообще нормально бы в рекурсию уйти - мы такую задачу на уроках делали, рекурсия там будет, рекурсия. :-/]]></description>
        <author>Fieral</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90682</guid>
        <pubDate>Sun, 15 Jun 2003 11:34:28 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90682</link>
        <description><![CDATA[DEiL: незачто :-)<br>хоть кому-то пригодилось ЭТО ;D]]></description>
        <author>DEiL</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90681</guid>
        <pubDate>Sun, 15 Jun 2003 09:34:55 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90681</link>
        <description><![CDATA[experimenter: все равно спасибо. 8D]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90679</guid>
        <pubDate>Sun, 15 Jun 2003 09:20:51 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90679</link>
        <description><![CDATA[DEiL: хм... да, ты прав - подстава..<br>блин]]></description>
        <author>DEiL</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90678</guid>
        <pubDate>Sun, 15 Jun 2003 09:17:45 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90678</link>
        <description><![CDATA[experimenter: <div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>DEiL, 15.06.03, 13:11:46</span><div class='quote '>ой, я кажется понял, о чём ты :-)<br><br>ты о &quot;abbccd&quot;<br>ну так тут просто - отождестви каждую букву из искомой перестановки с числом каким-нибудь.. например с её позицией в строке.<br>и уже работай с набором чисел. они уже не будут повторяться<br>и когда у тебя будет получена перестановка, сделаешь обратное - цифру заменишь на букву<br>вроде бы так..</div></div><br>а не получится, что у двух одинаковых перестановок будут разные представления?<br>]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90677</guid>
        <pubDate>Sun, 15 Jun 2003 09:12:43 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90677</link>
        <description><![CDATA[DEiL: читай выше :-)]]></description>
        <author>DEiL</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90676</guid>
        <pubDate>Sun, 15 Jun 2003 09:11:46 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90676</link>
        <description><![CDATA[DEiL: ой, я кажется понял, о чём ты :-)<br><br>ты о &quot;abbccd&quot;<br>ну так тут просто - отождестви каждую букву из искомой перестановки с числом каким-нибудь.. например с её позицией в строке.<br>и уже работай с набором чисел. они уже не будут повторяться<br>и когда у тебя будет получена перестановка, сделаешь обратное - цифру заменишь на букву<br>вроде бы так..]]></description>
        <author>DEiL</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90675</guid>
        <pubDate>Sun, 15 Jun 2003 09:10:26 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90675</link>
        <description><![CDATA[experimenter: <div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>DEiL, 15.06.03, 13:07:56</span><div class='quote '>ух<br>если что-нибудь останется загадкой - обращайся: у меня по этому всему экзамен в четверг ::)<br><br>&quot;а как быть-то если элементы повторяются?&quot; - в смысле?</div></div><br>насколько я понимаю, алгоритм работает для такого множества<br>(1,2,3,4) &lt;- генерим все перестановки для этого мн-ва<br>а для такого работает?<br>(1,2,2,3) &lt;- а для этого можем генерить?]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90674</guid>
        <pubDate>Sun, 15 Jun 2003 09:07:56 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90674</link>
        <description><![CDATA[DEiL: ух<br>если что-нибудь останется загадкой - обращайся: у меня по этому всему экзамен в четверг ::)<br><br>&quot;а как быть-то если элементы повторяются?&quot; - в смысле?]]></description>
        <author>DEiL</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90673</guid>
        <pubDate>Sun, 15 Jun 2003 09:06:04 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90673</link>
        <description><![CDATA[experimenter: спасибо! и хоть некоторые части тут сразу не совсем очевидны, тем не менее. <br>и потом, а как быть-то если элементы повторяются?<br>и потом... по сложности алгоритма, я имею в виду время, не тоже самое будет, как если бы мы просто перебирали эти шутовы перестановки?]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90672</guid>
        <pubDate>Sun, 15 Jun 2003 08:51:38 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90672</link>
        <description><![CDATA[DEiL: рассмотрим множество T(k) - произведение k множеств (с номерами от 1 до k), каждое из которых состоит из элементов от 0 до (k-i) (первое- 0,...,k-1, второе - 0,..,k-2, .., k-е - 0 )<br>очевидно, что мощность такого T(k) - k!<br>элемент, принадлежащий такому множеству представляется в виде (r1, &nbsp;...., rk)<br>в итоге T(k) - что-то вроде системы счисления с переменным основанием, т.е. для каждого (r1, &nbsp;...., rk) можно вычислить его номер (вроде так - n=r1*(k)+r2*(k)+..rk) и наоборот<br>пусть t1=(r1, .. , rk), t2=(R1, ... , Rk) - &nbsp;наборы из T(k); t1 &lt; t2, если до определённого i начала совпадают (r1=R1, .., r(i-1)=R(i-1)), а ri&lt;Ri<br>перебор... будем перебирать всё это счастье в &quot;естественном&quot; порядке: увеличивая ri на 1, если переполнение - увеличиваем r(i-1) на единицу и т.д..<br><br>таким образом мы умеем для T(k) вычислять его мощность, вычислять номер элемента (от 1 до k!), по номеру - сам элемент, и делать перебор<br><br>а теперь - гвоздь программы:<br>пусть P(k) - множество всех перестановок чисел от 1 до k<br>отождествим T(k) и P(k):<br>P(k)-&gt;T(k): возьмём перестановку (r1, ..., rk) и сопоставим ей элемент (t1, ..., tk) так:<br>для любого i от 1 до k найдем число значений, меньших ri среди r(i+1), r(i+2), ..., rk - это число возьмём за ti<br>( пример: (4,8,1,5,7,2,3,6) -&gt; (3,6,0,2,3,0,0,0) )<br>T(k)-&gt;P(k): меняя i от 1 до k, нужно просто помнить множество значений Si, которые ещё могут быть в перестановке на i-м месте<br>( пример: (3,6,0,2,3,0,0,0) -&gt; (4,8,1,5,7,2,3,6) : S1=1:8; t1=3 =&gt; r1=4 (именно четвёрке в множестве S1 предшествует 3 числа); убираем 4 из S1: S2=1:3+5:8, t2=6 =&gt; r2=8 =&gt; S3=1:3+5+7+8 и т.д...)<br><br>в итоге, чтобы перебрать все P(k), или по номеру получить перестановку, нужно сначала аналогичное действие сделать для T(k), а потом сопоставить по указанному выше правилу нужную перестановку<br><br>удачи :D]]></description>
        <author>DEiL</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90671</guid>
        <pubDate>Tue, 10 Jun 2003 18:32:49 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90671</link>
        <description><![CDATA[esperanto: Ты знаешь я кажется полгода назад писал подробный ответ на это дело в этом разделе<br><br>ответ сейчас не вспомню но можешь поискать<br>если конечно я не путаю]]></description>
        <author>esperanto</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90670</guid>
        <pubDate>Tue, 10 Jun 2003 18:04:40 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90670</link>
        <description><![CDATA[Demo_S: я решения проблемы не знаю....<br>но мысли имеются:<br>найти некоторые инвариант перестанвки, ну или параметр перестановки, зависящий от номера. например кол-во инверсий. &nbsp;на его основании выполнить все инверсии и поиметь перестановку.<br><br><br>кстати, почему не льзя заранее нагенерить, а потом по номеру из нагенеренного массива выдирать элемент. дешево и сердито:) (только места жрет)]]></description>
        <author>Demo_S</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90669</guid>
        <pubDate>Tue, 10 Jun 2003 14:14:46 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90669</link>
        <description><![CDATA[experimenter: <div class='tag-quote'><span class='tag-quote-prefix'>Цитата</span> <span class='tag-quote__quote-info'>vesper1, 10.06.03, 18:05:24</span><div class='quote '>Имхо это невозможно, без генерения... :'(</div></div><br>ну, как так? я вот в книге одной читал и там как раз таки строилось такое соответсвие, только книгу эта сейчас для меня недоступна. :-/<br>]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90668</guid>
        <pubDate>Tue, 10 Jun 2003 14:05:24 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90668</link>
        <description><![CDATA[vesper1: Имхо это невозможно, без генерения... :'(]]></description>
        <author>vesper1</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90667</guid>
        <pubDate>Tue, 10 Jun 2003 13:04:23 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90667</link>
        <description><![CDATA[experimenter: мужики, ну, давайте поднапряжемся и дадим мне ответ, а? плиз.]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      <item>
        <guid isPermaLink='true'>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90665</guid>
        <pubDate>Mon, 09 Jun 2003 19:01:37 +0000</pubDate>
        <title>ПерестаноBки</title>
        <link>https://forum.sources.ru/index.php?showtopic=9248&amp;view=findpost&amp;p=90665</link>
        <description><![CDATA[experimenter: есть строка из n букв, необязательно различных. <br>например,<br>abbccd<br>из этой строки можно нагенерить различные перестановки. генерить надо в лексографическом порядке. как смасрячить взаимнооднозначное соответсвие между номером перестановки при генерации и самой перестановкой?<br>выше написанная перестановка имеет номер 1, потом идет abbcdc под номером 2 и т.д.<br>генерить не предлагать, так как иногда времени не хватит.<br>зы<br>благодарен заранее]]></description>
        <author>experimenter</author>
        <category>Алгоритмы</category>
      </item>
	
      </channel>
      </rss>
	