<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Eurion · RainCT&#039;s Blog &#187; RainCT</title>
	<atom:link href="http://bloc.eurion.net/archives/author/RainCT/feed/" rel="self" type="application/rss+xml" />
	<link>http://bloc.eurion.net</link>
	<description>I would love to change the world, but they won&#039;t give me the source code...</description>
	<lastBuildDate>Sun, 29 Jan 2012 13:23:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Apunts de Teoria de la Computació: Gramàtiques incontextuals</title>
		<link>http://bloc.eurion.net/archives/2011/teoria-computacio-gramatiques-incontextuals/</link>
		<comments>http://bloc.eurion.net/archives/2011/teoria-computacio-gramatiques-incontextuals/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 22:11:36 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[formal-grammar]]></category>
		<category><![CDATA[language-theory]]></category>
		<category><![CDATA[theory-of-computation]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1823</guid>
		<description><![CDATA[Una gramàtica incontextual (CFG, Context Free Grammar) és un conjunt de regles de substitució on les parts esquerres són mots de longitud 1. Aquestes regles les anomenarem produccions i les seves parts esquerres variables (o no-terminals). Els símbols restants els anomenem terminals. Dues regles com per exemple i es poden representar de forma agrupada de [...]]]></description>
			<content:encoded><![CDATA[<p>Una <strong>gramàtica incontextual</strong> (CFG, <em>Context Free Grammar</em>) \(G\) és un conjunt de regles de substitució on les parts esquerres són mots de longitud 1. Aquestes regles les anomenarem <em>produccions</em> i les seves parts esquerres <em>variables</em> (o <em>no-terminals</em>). Els símbols restants els anomenem <em>terminals</em>.</p>
<p>Dues regles com per exemple \(S \rightarrow aS\) i \(S \rightarrow X\) es poden representar de forma agrupada de la següent manera: \(S \rightarrow aS | X\).</p>
<p>En una gramàtica sempre hi ha una variable (normalment la primera que apareix) que anomenem <em>símbol inicial</em>. Les paraules generades per la gramàtica són aquelles formades per <em>terminals</em> a les quals es pot arribar des del símbol inicial.</p>
<p>Podem representar les substitucions necessàries per arribar a una paraula amb la sintaxi ja coneguda, o bé en forma d&#8217;arbre (<i>arbre de derivació</i> o <i>arbre sintàctic</i>).</p>
<p>Les gramàtiques incontextuals també es poden representar formalment com una tupla \(G=\langle{}V,\Sigma,\delta,S\rangle\).</p>
<p>Un llenguatge s&#8217;anomena <strong>llenguatge incontextual</strong> si existeix una gramàtica que el genera. Existeixen algorismes \(O(n^3)\) per comprovar si una paraula és generable per una gramàtica i generar-ne l&#8217;arbre sintàctic. Això és útil per a compiladors i intèrprets.</p>
<p>Quan una gramàtica permet més d&#8217;un arbre de derivació per a una paraula diem que és ambigua. Això no és desitjable quan volem utilitzar la gramàtica per interpretar el significat de les entrades.</p>
<p>Un criteri per determinat l&#8217;ambigüitat quan només utilitzem <i>regles lineals</i> (on cada alternativa de la part dreta només inclou una única variable): si no existeixen dues alternatives amb que es pugui generar el mateix, llavors la regla no genera ambigüitat.</p>
<p>
<hr /></p>
<h4>Operacions sobre gramàtiques</h4>
<p></p>
<p>Els llenguatges incontextuals estan tancats per unió: Tenim dues CFG \(G_1\) i \(G_2\) que generen els llenguatges \(\mathcal{L}(G_1)=L_1\) i \(\mathcal{L}(G_2)=L_2\). Suposem que els llenguatges no comparteixen variables (si no fos així, les podem reanomenar). Si definim la operació <i>unió de gramàtiques</i> \(G_1\cup G_2=\langle V_1 \cup V_2 \cup \{S\}, \Sigma_1 \cup \Sigma_2, \delta_1 \cup \delta_2 \cup \{S \rightarrow S_1|S_2, S\}\rangle\) llavors aquesta compleix \(\mathcal{L}(G_1 \cup G_2) = \mathcal{L}(G_1) \cup \mathcal{L}(G_2) = L_1 \cup L_2\).</p>
<p>També ho són per <i>concatenació</i>. Amb les mateixes condicions que abans, \((G_1\cdot G_2)=\langle V_1 \cup V_2 \cup \{S\}, \Sigma_1 \cup \Sigma_2, \delta_1 \cup \delta_2 \cup \{S \rightarrow S_1S_2\}, S\rangle\) compleix \(\mathcal{L}(G_1\cdot G_2)=\mathcal{L}(G_1)\cdot \mathcal{L}(G_2)=L_1\cdot L_2\).</p>
<p>Per l&#8217;operació estrella: \(G^*=\langle V \cup \{S&#8217;\}, \Sigma, \delta \cup \{S&#8217; \rightarrow S&#8217;S|\lambda\}, S&#8217;\rangle\) compleix \(\mathcal{L}(G^*)=\mathcal{L}(G)^*=L^*\).</p>
<p>Per l&#8217;operació <i>revessat</i>: \(G^R=\langle V, \Sigma, \{X \rightarrow u^R | (X \rightarrow u) \in \delta\}, S&#8217;\rangle\) compleix \(\mathcal{L}(G^R)=\mathcal{L}(G)^R=L^R\) ja que \(\forall X \in V, \mathcal{L}(G, X)^R \subseteq \mathcal{L}(G^R,X)\).</p>
<p>I per <i>imatge de morfisme</i>: \(L \in CFL\) i \(\sigma: \Sigma_1 \rightarrow \Sigma_2\) tal que \(\sigma(uv)=\sigma(u)\sigma(v) \Rightarrow \sigma(L) \in CFL\). En aquest cas a la tupla de la gramàtica resultant es substitueix \(\delta\) per \(\{X\rightarrow \sigma(u) | (X \rightarrow u) \in \delta\}\).</p>
<p>En canvi, no són tancats per intersecció (si \(L_1, L_2 \in CFL \nRightarrow (L_1 \cap L_2) \in CFL\)) ni complementari.</p>
<p><em>Aquests apunts estan basats en els vídeos de <a href="http://www.lsi.upc.edu/~ggodoy/tc.html">Teoria de la Computació</a> de Guillem Godoy (UPC).</em></p>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/computacio-teoria-de-llenguatges/' rel='bookmark' title='Apunts de Teoria de la Computació: Teoria de llenguatges'>Apunts de Teoria de la Computació: Teoria de llenguatges</a> <small>Un alfabet () és un conjunt finit d&#8217;elements (símbols), habitualment...</small></li>
</ol></p> <p><a href="http://bloc.eurion.net/?flattrss_redirect&amp;id=1823&amp;md5=c10f316096733973814e443127bc8040" title="Flattr" target="_blank"><img src="http://bloc.eurion.net/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/teoria-computacio-gramatiques-incontextuals/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apunts de Teoria de la Computació: Teoria de llenguatges</title>
		<link>http://bloc.eurion.net/archives/2011/computacio-teoria-de-llenguatges/</link>
		<comments>http://bloc.eurion.net/archives/2011/computacio-teoria-de-llenguatges/#comments</comments>
		<pubDate>Thu, 06 Oct 2011 12:49:05 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[formal-grammar]]></category>
		<category><![CDATA[language-theory]]></category>
		<category><![CDATA[theory-of-computation]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1767</guid>
		<description><![CDATA[Un alfabet () és un conjunt finit d&#8217;elements (símbols), habitualment caràcters alfanumèrics. Un mot és una llista de símbols d’un alfabet. El mot buit (llista de longitud 0) el denotarem amb el meta-símbol . Utilitzarem , , , , &#8230; per denominar paraules. Paraules: ab, bbb, a, Longituds: &#124;ab&#124;=2, &#124;bbb&#124;=3, &#124;a&#124;=1, &#124;&#124;=0 Extenem la notació [...]]]></description>
			<content:encoded><![CDATA[<p>Un <strong>alfabet</strong> (\(\Sigma\)) és un conjunt finit d&#8217;elements (símbols), habitualment caràcters alfanumèrics.</p>
<p>Un <em>mot</em> és una llista de símbols d’un alfabet. El mot buit (llista de longitud 0) el denotarem amb el meta-símbol \(\lambda\). Utilitzarem \(u\), \(v\), \(w\), \(u_1\), &#8230; per denominar paraules.</p>
<p style="margin-left: 50px;">
  \(\Sigma = \{a, b\}\)<br />
  Paraules: ab, bbb, a, \(\lambda\)<br />
  Longituds: |ab|=2, |bbb|=3, |a|=1, |\(\lambda\)|=0
</p>
<p>Extenem la notació de les longituds per a occurències d’un mot dins d’un altre: \(|u|_w\)</p>
<p style="margin-left: 50px;">
  \(|ab|_a=1\), \(|bbb|_b=3\), \(|bbb|_{bb}=2\)
</p>
<p>Per referir-nos al símbol i-éssim del mot u utilitzarem: u[i]</p>
<p style="margin-left: 50px;">
  ab[1] = a, ab[2] = b
</p>
<p>Amb la operació producte (\(u\cdot v\) o \(uv\)) representem la concatenació de dues paraules. Per exemple:</p>
<p style="margin-left: 50px;">
  \((ab)\cdot(bbb) = abbbb\)<br />
  Element neutre: \(u\cdot\lambda=\lambda\cdot u=u\)<br />
  Associativitat: \(u\cdot(v\cdot w)=(u\cdot v)\cdot w\)
</p>
<p>
Amb \(\Sigma^*\) representem el conjunt de tots els mots possibles que podem construir amb l’alfabet \(\Sigma\). Exemple per a \(\Sigma = \{a, b\}\):</p>
<p><span id="more-1767"></span></p>
<p style="margin-left: 50px;">
  \(\Sigma^*={\lambda, a, b, aa, ab, ba, bb, &#8230;}\)
</p>
<p>Un llenguatge sobre l’alfabet \(\Sigma\) és un subconjunt qualsevol \(L^* \subseteq \Sigma^*\). Per exemple:</p>
<ul>
<li>
  Paraules sobre l’alfabet {a, b} i de longituds múltiples de 2:<br />
  &nbsp; &nbsp;\(\{w \in \{a, b\}^* / |w| \in \dot{2}\} = \{\lambda, aa, ab, ba, bb, aaaa, &#8230;\}\)
</li>
<li>
  Paraules amb algun símbol «a»:<br />
  &nbsp; &nbsp;\(\{w \in \{a,b\}^* / \exists w_1,w_2 : w = w_1aw_2\} = \{w \in \{a, b\}^* / |w|_a \ge 1\}\)
</li>
<li>
  Paraules tals que tota ocurrència d’«a» ve seguida d’una occurència de «b»:<br />
  &nbsp; &nbsp;\(\{w \in \{a,b\}^* / \forall w_1, w_2 : (w=w_1aw_2 \Rightarrow \exists w_2^1 : w_2 = bw_2^1) = \)<br />
  &nbsp; &nbsp;\( = \{w \in \{a, b\}^* / |w|_{aa}=0\land(w=\lambda \lor \exists w&#8217; : w=w&#8217;b)\}\)
</li>
<p>
<hr /></p>
<p>Denotem el llenguatge que conté només el mot buit amb \(\Lambda=\{\lambda\}\) (\(\Lambda \neq \emptyset\)).</p>
<p>Definim la concatenació de dos llenguatges:</p>
<p style="margin-left: 50px;">
  \(L_1\cdot L_2 = \{w_1\cdot w_2 / w_1 \in L_1 \land w_2 \in L_2\}=\) \(\{w / \exists w_1 \in L_1, w_2 \in L_2 : (w=w_1w_2)\}\)</p>
<p>  Exemples:
  </p>
<p style="margin-left: 50px;">
    \(\{a,bb\}\cdot\{b,ba\} = \{ab, aba, bbb, bba\}\)<br />
    Element neutre: \(\Lambda\cdot L = L \cdot \Lambda = L\)<br />
    No funciona amb el conjunt buit: \(\emptyset\cdot L=L\cdot \emptyset = \emptyset\)<br />
    Associativitat: \(L_1(L_2L_3)=(L_1L_2)L_3\)
  </p>
<p>Definim l&#8217;exponenciació de paraules:</p>
<p style="margin-left: 50px;">
  \(w^n=w\cdot w\cdot \cdot\cdot\cdot \cdot w\)</p>
<p>  Exemples:
  </p>
<p style="margin-left: 50px;">
    \(w^2=ww\)  \(w^1=w\)  \(w^0=\lambda\)
  </p>
<p>  Es compleix que: \(w^n=w\cdot w^{n-1}\), \(n\ge 1\).</p>
<p>Ídem per a l&#8217;exponenciació de llenguatges.</p>
<p>Definim també l&#8217;operació \(L^*\) (<a href="http://ca.wikipedia.org/wiki/Clausura_de_Kleene">clausura de Kleene</a>) d&#8217;un llenguatge. Aquesta dóna com a resultat un nou llenguatge que conté aquelles paraules que es poden obtenir a base d&#8217;escollir un nombre finit de paraules d&#8217;L i concatenar-les.</p>
<p style="margin-left: 50px;">
  \(<br />
    \begin{array}{ll}L^*<br />
      &#038; = \{w_1\cdot w_2\cdot \cdot\cdot\cdot \cdot w_n / w_1, w_2, &#8230;, w_n \in L\} \\<br />
      &#038; = \{L^0\cup L^1\cup L^2\cup &#8230;\}\\<br />
      &#038; = \prod_{n=0}^{\infty}L^n\\<br />
    \end{array}<br />
  \)<br />
  (Les paraules d&#8217;\(L^*\) són concatencions de 0, 1, 2, &#8230; paraules d&#8217;L.)</p>
<p>  Per exemple:
  </p>
<p style="margin-left: 50px;">
    \(\{a\}^* = \{\lambda, a, aa, aaa, &#8230;\}\)<br />
    \(\{ab\}^* = \{\lambda, ab, abab, ababab, &#8230;\}\)<br />
    \(\{a, bb\}^* = \{\lambda, a, bb, aa,  abb, bba, bbbb, &#8230;\}\)<br />
    \(\{w\in\{a,b\}^* / |w| \in \dot{2}\}^* = \{w\in\{a,b\}^* / |w| \in \dot{2}\}\)
  </p>
<p>De forma semblant definim l&#8217;operació \(L^+\), la qual no obliga a incloure el mot buit.</p>
<p style="margin-left: 50px;">
  \(L^+ = L^1\cup L^2\cup&#8230;\)<br />
  \(L^* = L^+ \cup \{\lambda\}\)<br />
  \(\lambda \in L^+ \Leftrightarrow \lambda \in L\)
</p>
<p>
<hr /></p>
<p>Denominem el <em>revessat</em> d&#8217;un mot \(w\): \(w^R\). Exemple:</p>
<p style="margin-left: 50px;">
  \((aabab)^R=babaa\)
</p>
<p>El revessat de la concatenació de dues paraules correspon al revessat de les dues paraules:</p>
<p style="margin-left: 50px;">
  \((uv)^R=v^Ru^R\)
</p>
<p>També tenim el revessat d&#8217;un llenguatge:</p>
<p style="margin-left: 50px;">
  \(L^R = \{w^R / w \in L\} = \{w | w^R \in L\}\)<br />
  \((L_1L_2)^R=L_2^RL_1^R\)</p>
<p>  Per exemple:
  </p>
<p style="margin-left: 50px;">
    \(\{aw | w \in \{a, b\}^*\}^R = \{wa | w \in \{a,b\}^*\}\)
  </p>
<p>Definim un <strong>morfisme</strong> com una funció que transforma paraules d&#8217;un alfabet a un altre:</p>
<p style="margin-left: 50px;">
  \(\sigma: \Sigma_1^* \rightarrow \Sigma_2^*\)<br />
  Commutativa amb la concatenació: \(\sigma(uv) = \sigma(u)\sigma(v)\)
</p>
<p style="margin-left: 50px;">
  \(\sigma(a_1a_2\cdot\cdot\cdot a_n)=\sigma(a_1)\sigma(a_2)\cdot\cdot\cdot\sigma(a_n)\)<br />
  \(\sigma(\lambda)=\lambda\)
</p>
<p>Gràcies a la commutativitat, tenim prou per definir un morfisme amb definir la imatge dels símbols de l’alfabet, ja que llavors l’imatge de qualsevol mot es pot calcular en termes de les imatges dels símbols.</p>
<p>Per exemple:</p>
<p style="margin-left: 50px;">
  \(\sigma: \{a, b, c\}^* \rightarrow \{0, 1\}^*\)<br />
  \(\sigma(a) = 0\), \(\sigma(b)=11\), \(\sigma(c)=\lambda\)
</p>
<p style="margin-left: 50px;">
  \(\begin{array}{ll}<br />
    \sigma(accbacb)<br />
    &#038; =  \sigma(a)\sigma(c)\sigma(c)\sigma(b)\sigma(a)\sigma(c)\sigma(b) \\<br />
    &#038; = 0\lambda\lambda110\lambda11 \\<br />
    &#038; = 011011<br />
  \end{array}<br />
  \)
</p>
<p>Per a un llenguatge L:</p>
<p style="margin-left: 50px;">
  \(\sigma: \Sigma_1^* \rightarrow \Sigma_2^*\)<br />
  \(L \subseteq \Sigma_1^*\) &nbsp; \(\sigma(L)=\{\sigma(w) / w \in L\}\)<br />
  \(L \subseteq \Sigma_2^*\) &nbsp; \(\sigma^{-1}(L) = \{w / \sigma(w) \in L\}\)<br />
  \(\sigma(L_1L_2) = \sigma(L_1)\sigma(L_2)\)
</p>
<p>Una <strong>regla de reescriptura</strong> (o <em>substitució</em>) és un parell de paraules \(u\rightarrow v\). Per exemple, la regla \(ab \rightarrow bba\) substitueix tota ocurrència d&#8217;«ab» per «bba».</p>
<p>Representem una substitució de la forma \(w_1uw_2 \rightarrow_{u\rightarrow v} w_1vw_2\). Per exemple:</p>
<p style="margin-left: 50px;">
  \(a\underline{ab}ab \rightarrow_{ab\rightarrow bba} a\underline{bba}ab\)
</p>
<p>Si R és un conjunt de regles, podem indicar que \(w\) es transforma en \(w&#8217;\)&#8230;</p>
<table>
<tr>
<td>\(w\rightarrow_R w&#8217;\)</td>
<td>\(w\rightarrow_R^* w&#8217;\)</td>
<td>\(w\rightarrow_R^+ w&#8217;\)</td>
<td>\(w\rightarrow_R^i w&#8217;\)</td>
</tr>
<tr>
<td>aplicant 1 regla d&#8217;R</td>
<td>aplicant 0 o mes substitucions amb regles d&#8217;R</td>
<td>aplicant 1 o més substitucions amb regles d&#8217;R</td>
<td>aplicant \(i\) substitucions amb regles d&#8217;R</td>
</tr>
</table>
<p></p>
<p><em>Aquests apunts estan basats en els vídeos de <a href="http://www.lsi.upc.edu/~ggodoy/tc.html">Teoria de la Computació</a> de Guillem Godoy (UPC).</em></ul>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/teoria-computacio-gramatiques-incontextuals/' rel='bookmark' title='Apunts de Teoria de la Computació: Gramàtiques incontextuals'>Apunts de Teoria de la Computació: Gramàtiques incontextuals</a> <small>Una gramàtica incontextual (CFG, Context Free Grammar) és un conjunt...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/calcul-funcions-duna-variable/' rel='bookmark' title='Apunts de Càlcul: Funcions d&#8217;una variable'>Apunts de Càlcul: Funcions d&#8217;una variable</a> <small>Introducció Considerem una funció real de variable real tal que...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-calcul-cost-algorismes/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs'>Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs</a> <small>Introducci&oacute; Els algorismes s&oacute;n per tot arreu i per aix&ograve;...</small></li>
</ol></p> <p><a href="http://bloc.eurion.net/?flattrss_redirect&amp;id=1767&amp;md5=f48e42687c8c07843c5b813ccce00f2a" title="Flattr" target="_blank"><img src="http://bloc.eurion.net/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/computacio-teoria-de-llenguatges/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apunts de Bases de Dades</title>
		<link>http://bloc.eurion.net/archives/2011/apunts-de-bases-de-dades/</link>
		<comments>http://bloc.eurion.net/archives/2011/apunts-de-bases-de-dades/#comments</comments>
		<pubDate>Wed, 20 Jul 2011 18:35:02 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[databases]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1206</guid>
		<description><![CDATA[Introducci&#243; Els tres mons M&#243;n &#160; Disseny&#8230; (BD) Enginyeria del Software Depend&#232;ncia tecnol&#242;gica M&#243;n real objectes del m&#243;n real conceptual especificaci&#243; independent M&#243;n conceptual coneixements / informaci&#243; M&#243;n de les representacions dades l&#242;gic i f&#237;sic disseny dependent M&#243;n conceptual Classes d&#39;objectes: quelcom real, identificable i distingible. &#8230; [FIXME: imatge diagrama UML] &#8230; M&#243;n de les [...]]]></description>
			<content:encoded><![CDATA[<h3>Introducci&oacute;</h3>
<h4>Els tres mons</h4>
<table border="1" style="margin-top: 1em; margin-bottom: 1em;">
<thead>
<tr>
<td style="text-align: center; ">M&oacute;n</td>
<td>&nbsp;</td>
<td style="text-align: center; ">Disseny&#8230; (BD)</td>
<td style="text-align: center; ">Enginyeria del Software</td>
<td style="text-align: center; ">Depend&egrave;ncia tecnol&ograve;gica</td>
</tr>
</thead>
<tbody>
<tr>
<td><strong>M&oacute;n real</strong></td>
<td><em>objectes del m&oacute;n real</em></td>
<td rowspan="2" style="text-align: center; ">conceptual</td>
<td rowspan="2" style="text-align: center; ">especificaci&oacute;</td>
<td rowspan="2" style="text-align: center; ">independent</td>
</tr>
<tr>
<td><strong>M&oacute;n conceptual</strong></td>
<td><i>coneixements / informaci&oacute;</i></td>
</tr>
<tr>
<td><strong>M&oacute;n de les representacions</strong></td>
<td><em>dades</em></td>
<td style="text-align: center; ">l&ograve;gic i f&iacute;sic</td>
<td style="text-align: center; ">disseny</td>
<td style="text-align: center; ">dependent</td>
</tr>
</tbody>
</table>
<h5>M&oacute;n conceptual</h5>
<p>Classes d&#39;objectes: quelcom real, identificable i distingible.</p>
<p>&#8230; [FIXME: imatge diagrama UML] &#8230;</p>
<h5>M&oacute;n de les representacions</h5>
<p>El m&eacute;s obvi seria utilitzar fitxers (i directoris), per&ograve; aquests no es permeten representar associacions tal com nosaltres volem. Per aquest motiu, neix el concepte de&nbsp;<strong>base de dades</strong>: un <u>conjunt estructurat de dades</u> que permet representar classes d&#39;objectes i les seves associacions amb <u>integraci&oacute;</u> (sense repeticions) i <u>compartici&oacute;</u> (molts usuari alhora) de dades.</p>
<h6>Evoluci&oacute;:</h6>
<ul>
<li>Model jer&agrave;rquic: arbres (IBM). Tenen el problema que un fill pot tenir nom&eacute;s un sol pare.</li>
<li>Model en xarxa: xarxes.</li>
<li>Model relacional (1969,&nbsp;<a href="http://ca.wikipedia.org/wiki/Edgar_F._Codd">Codd</a>): <u>taules</u>.</li>
</ul>
<h4>SGBD (<em>DBMS</em>)</h4>
<p>Un <strong>sistema gestor de bases de dades</strong>&nbsp;(<em>database management system</em>) &eacute;s un programa complex que facilita la representaci&oacute; de classes d&#39;objectes i les seves associacions i diverses tasques de gesti&oacute; de dades als programes d&#39;aplicaci&oacute;. Nosaltres utilitzarem el <em>PostgreSQL</em>.</p>
<p><span id="more-1206"></span></p>
<h3>El model relacional</h3>
<h4>Objectius i origens</h4>
<p>Origen: E. F. Codd, 1969.</p>
<p>Primers prototipus: al comen&ccedil;ament dels anys 80.</p>
<p>Objectius: Facilita que la base de dades sigui percebuda com una estructura l&ograve;gica independent de l&#39;estructura f&iacute;sica, simple i uniforme.</p>
<h4>Estructura de les dades</h4>
<p><a href="http://bloc.eurion.net/wp-content/uploads/2011/07/Estructura-de-dades.png"><img src="http://bloc.eurion.net/wp-content/uploads/2011/07/Estructura-de-dades.png" alt="" title="Estructura de dades" width="371" height="163" class="alignright size-full wp-image-1698" style="margin-top: 0;" /></a></p>
<table border="1">
<thead>
<tr>
<td><strong>Model relacional</strong></td>
<td><strong>SQL (ANSI)</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td>Relacions</td>
<td>Taules</td>
</tr>
<tr>
<td>Atributs</td>
<td>Columnes</td>
</tr>
<tr>
<td>Tuples</td>
<td>Files</td>
</tr>
</tbody>
</table>
<p>Una <strong>relaci&oacute;</strong> es compon de:</p>
<ul>
<li><strong>Esquema</strong> de la relaci&oacute; (intensi&oacute;) (cap&ccedil;alera)<br />
		&Eacute;s el nom de la relaci&oacute; i els seus <strong>atributs</strong>. Per exemple: &laquo;estudiants(codi, dni, nom, tel&egrave;fon)&raquo;.</p>
<ul>
<li><strong>Atribut</strong>: &eacute;s el paper o rol que juga un <strong>domini</strong> en una relaci&oacute;.</li>
<li><strong>Domini</strong>: &eacute;s un conjunt de valors at&ograve;mics. Per exemple: &laquo;int&raquo;, &laquo;char(30)&raquo;, etc.</li>
<li><strong>Valors nuls</strong>: (SQL: <em>NULL</em>) desconegut i inaplicable.</li>
</ul>
</li>
<li><strong>Extensi&oacute;</strong> de la relaci&oacute;<br />
		L&#39;extensi&oacute; d&#39;una relaci&oacute; d&#39;esquema R(A1, A2, &#8230;, An) &eacute;s un conjunt de <strong>tuples</strong> Tj=&lt;V11, V12, &#8230;, Vn&gt;, on Vij &eacute;s un valor del domini d&#39;Aj o b&eacute; un valor nul.</p>
<ul>
<li><strong>Tupla</strong>: &eacute;s un element de l&#39;extensi&oacute; de la relaci&oacute;.</li>
<li><strong>Grau</strong>: &eacute;s el nombre d&#39;atributs d&#39;una relaci&oacute;.</li>
<li><strong>Cardinalitat</strong>: &eacute;s el nombre de tuples d&#39;una relaci&oacute;.</li>
</ul>
</li>
</ul>
<p>Una relaci&oacute; ha de contenir valors at&ograve;mics (un sol valor), no hi ha tuples repetides i no hi ha ordre entre les tuples ni entre els atributs.</p>
<p><strong>Superclau</strong>: &eacute;s un subconjunt dels atributs de l&#39;esquema de la relaci&oacute; que identifica les tuples de l&#39;extensi&oacute; de la relaci&oacute;.</p>
<p><strong>Clau</strong> (claus candidates): &eacute;s una superclau d&#39;una relaci&oacute; que no t&eacute; cap subconjunt propi que sigui alhora superclau. Es divideixen en la <strong>clau prim&agrave;ria</strong> (la clau candidata que hagi estat escollida) i <strong>claus secund&agrave;ries </strong>o alternatives.</p>
<p><strong>Clau forana</strong>: subconjunt dels atributs de l&#39;esquema de la relaci&oacute; que referencia una clau prim&agrave;ria d&#39;una altre relaci&oacute; o de la pr&ograve;pia relaci&oacute;.</p>
<h4>Regles d&#8217;integritat</h4>
<ul>
<li>
<p><strong>Regla d&#8217;integritat d&#8217;entitat</strong></p>
<p>Una clau primària d&#8217;una relació no pot tenir ni valors nuls ni valors repetits.</p>
</li>
<li>
<p><strong>Regla d&#8217;integritat referencial</strong></p>
<p>Els valors d&#8217;una clau forana poden ser només valors de la clau primària referenciada o valors nuls.</p>
<p>Polítiques d&#8217;actuació en cas d&#8217;esborrat o modificació de claus primàries amb claus foranes referenciant-les:
<ul>
<li><strong>Restricció</strong>: no es permet esborrar o modificar una clau primària referenciada per claus foranes (SQL: RESTRICT / NOACTION).</li>
<li><strong>Actualització en cascada</strong>: en cas d&#8217;esborrar o modificar una clau primària referenciada en alguna clau forana, s&#8217;esborren o modifiquen totes les referències (SQL: CASCADE).</li>
<li><strong>Anul&middot;lació</strong>: en cas d&#8217;esborrar o modificar una clau primària referenciada s&#8217;assignen valors nuls a totes les referències (SQL: SET NULL / SET DEFAULT).</li>
</ul>
</li>
<li>
<p><strong>Regla d&#8217;integritat de domini</strong></p>
<ol>
<li>Un valor no nul d&#8217;un atribut ha de pertànyer al domini de l&#8217;atribut.</li>
<li>Les operacions que es poden aplicar sobre els valors depenen dels dominis dels valors.</li>
</ol>
</li>
</ul>
<h3>Àlgebra relacional</h3>
<table border="0" class="noborder">
<tr>
<td>Unió</td>
<td>R=TAULA1&cup;TAULA2</td>
<td>uneix tots els resultats de dues taules amb columnes compatibles</td>
</tr>
<tr>
<td>Reanomenament</td>
<td colspan="2">R=TAULA1{foo->bar, meh->moh}</td>
</tr>
<tr>
<td>Intersecció</td>
<td>R=T1&cap;T2</td>
<td>torna els resultats coincidents de les dues taules</td>
</tr>
<tr>
<td>Diferència</td>
<td>R=T1-T2</td>
<td>suprimeix els resultats de T1 coincidents en T2</td>
</tr>
<tr>
<td>Producte cartesià</td>
<td>R=T1xT2</td>
<td>combina tots els resultats de 2 taules (no compatibles)</td>
</tr>
<tr>
<td>Selecció</td>
<td colspan="2">R=T1(superfície>16, mòdul=&#8217;B2&#8242;)</td>
</tr>
<tr>
<td>Projecció</td>
<td colspan="2">R=T1[nom, ciutat]</td>
</tr>
<tr>
<td colspan="3">&nbsp;</td>
</tr>
<tr>
<td>Combinació (<em>join</em>)</td>
<td>R=EMPLEATS[despatx=id]DESPATXOS</td>
<td>combina i torna els resultats combinats</td>
</tr>
<tr>
<td style="vertical-align: top;"><em>Natural join</em></td>
<td style="vertical-align: top;">R=EMPLEATS[despatx*id]DESPATXOS<br />EMPLATS*DESPATXOS <small>(si les columnes tenen el mateix nom)</small></td>
<td style="vertical-align: top;">els resultats només contenen «despatx» i no l&#8217;«id» duplicat</td>
</tr>
</table>
<h3>Components lògics d&#8217;una base de dades</h3>
<p>Un <strong>esquema</strong>, per a un SGBD, és un conjunt <strong>definit</strong> i relacionat de components de dades i components de control.</p>
<table border="0" class="noborder">
<tr>
<td style="vertical-align: top;">
<pre>
CREATE SCHEMA nom_esquema
AUTHORIZATION identitat_usuari
[llista d'elemens de l'esquema]
</pre>
<p>Esborrat d&#8217;esquema:</p>
<pre>DROP SCHEMA nom_esquema RESTRICT/CASCADE</pre>
</td>
<td style="vertical-align: top;">Alternativament, en implementacions no estàndards:</p>
<pre>
CREATE DATABASE
CREATE DM
</pre>
</td>
</tr>
</table>
<h5>Connexions</h5>
<pre>CONNECT TO nom_servidor [AS nom_connexió] [USER ...]
DISCONNECT nom_connexió DEFAULT/CURRENT/ALL</pre>
<h5>Sessió</h5>
<pre>SET SESSION CHARACTERISTICS AS mode_trans</pre>
<h5>Transaccions</h5>
<pre>SET TRANSACTION mode_trans / START TRANSACTION
mode_trans: mode d'accés / nivell d'aïllament (READONLY / READ WRITE)
</pre>
<pre>
COMMIT: s'accepta tot.
</pre>
<pre>
ROLLBACK: no s'accepta res (es desfan els canvis).</pre>
<h5>Dominis</h5>
<pre>CREATE DOMAIN ciutats AS CHAR(15)
DEFAULT 'BCN'
CONSTRAINT ciutats_valides CHECK VALUE IN ('BCN', 'GIR', 'TGN')
</pre>
<h5>Taules</h5>
<pre>
CREATE TABLE empleats(
  codi_empl INTEGER PRIMARY KEY,
  nom_empl VARCHAR(30),
  dni CHAR(8) UNIQUE,
  sou REAL NOT NULL,
  data_naix DATE CONSTRAINT naix_impossible CHECK (data_naix >= 01/01/1900),
  data_jubilacio DATE,
  ciutat_resid CIUTATS,
  dept INTEGER DEFAULT 1 REFERENCES departaments(id)
</pre>
<p>Aquesta última referència també s&#8217;hauria pogut especificar al final:</p>
<pre>FOREIGN KEY (dept) REFERENCES departaments(id) [ON DELETE ...] [ON UPDATE ...]</pre>
<h5>Assercions</h5>
<p>Ens permeten definir restriccions d&#8217;integritat a més d&#8217;una taula. Es comproven sempre. SQL:
<pre>CREATE ASSERTION nom CHECK (condition)</pre>
<p>No estan implementades en cap SBGD, ja que disposen de <small>TRIGGER</small> (disparadors) que permeten la mateixa funcionalitat i són més potents.</p>
<h5>Vistes (esquemes externs)</h5>
<p>Una vista és una relació (es pot consultar i <em>actualitzar</em>) <strong>derivada</strong> (no existeix físicament, sinó que és <em>virtual</em>).</p>
<pre>CREATE VIEW nom (nom_col1, nom_col2, ...., nom_coln) AS <consulta SQL> [WITH CHECK OPTION]</consulta></pre>
<h5>Procediments (<em>PL/pgSQL</em>)</h5>
<pre>
CREATE FUNCTION troba_ciutat(dni_ciutat VARCHAR(9)) RETURNS VARCHAR(15) AS $$
DECLARE
  ciutat_client VARCHAR(15);
BEGIN
  SELECT ciutat INTO ciutat_client
    FROM empleats
    WHERE dni=dni_client;
  RETURN ciutat_client;
END;
$$LANGUAGE plpgsql;
</pre>
<h5>Disparadors (<em>triggers</em>)</h5>
<pre>
CREATE TRIGGER nom_disparador
  BEFORE UPDATE ON nom_taula
  FOR EACH ROW EXECUTE PROCEDUR acció;
</pre>
<h5>Privilegis</h5>
<pre>
GRANT privilegis ON objectes TO usuaris [WITH GRANT OPTION]
REVOKE [GRANT OPTION FOR] privilegis ON objects FROM usuaris [CASCADE|RESTRICT]
GRANT PUBLIC ...
</pre>
<pre>
CREATE ROLE nom;
SET ROLE nom;
</pre>
<h3>Traducció de disseny a model relacional</h3>
<p>La següent taula resumeix com transformar els elements d&#8217;un disseny UML per tal d&#8217;implementar-lo com a base de dades en un SGBD:</p>
<table>
<tr>
<th>Model semàntic</th>
<th>Model relacional</th>
</tr>
<tr>
<td>Classes d&#8217;objectes</td>
<td>Relació</td>
</tr>
<tr>
<td>Associació binària un a molts</td>
<td>Clau forana</td>
</tr>
<tr>
<td>Associació binària un a un</td>
<td>Clau forana</td>
</tr>
<tr>
<td>Associació binària molts a molts</td>
<td>Relació</td>
</tr>
<tr>
<td>Associació unària</td>
<td>Relació</td>
</tr>
<tr>
<td>Associació recursiva</td>
<td>(Igual que les altres)</td>
</tr>
<tr>
<td>Classe associativa</td>
<td>TODO: imatge&#8230;</td>
</tr>
</table>
<h3>Transaccions i concurrència</h3>
<h4>Transaccions</h4>
<p><strong>ACID</strong>: atomicitat, consistència, «isolació», durabilitat.</p>
<p>Tipus d&#8217;interferències entre transaccions:
<ul>
<li>actualització perduda (doble actualització)</li>
<li>lectura no confirmada</li>
<li>lectura no repetible</li>
<li>anàlisi inconsistent</li>
<li>fantasmes</li>
</ul>
<h4>Serialitzabilitat</h4>
<p>La teoria de la serialitzabilitat defineix de manera precisa les condicions que s&#8217;han de complir per considerar que les transaccions estan aïllades entre si correctament.</p>
<p>&#8230;</p>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/eda-diccionaris/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Diccionaris'>Apunts d&#8217;Estructures de Dades i Algorismes: Diccionaris</a> <small>Introducci&oacute; S&oacute;n un tipus abstracte de dades (TAD), &eacute;s a...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-p-np/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Les classes de problemes P i NP'>Apunts d&#8217;Estructures de Dades i Algorismes: Les classes de problemes P i NP</a> <small>Classes de problemes &ndash; P i NP Entrades Problemes Classes...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-programacio-dinamica/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Programació dinàmica'>Apunts d&#8217;Estructures de Dades i Algorismes: Programació dinàmica</a> <small>1. Nombres de Fibonacci L&#39;algorisme trivial per al c&agrave;lcul dels...</small></li>
</ol></p> <p><a href="http://bloc.eurion.net/?flattrss_redirect&amp;id=1206&amp;md5=8973d330d7bf6f0a531af5023bc170be" title="Flattr" target="_blank"><img src="http://bloc.eurion.net/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/apunts-de-bases-de-dades/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Trigonometria: Sinus, cosinus i tangent dels angles 30º, 45º i 60º</title>
		<link>http://bloc.eurion.net/archives/2011/trigonometria-sin-cos-tan-30-45-60/</link>
		<comments>http://bloc.eurion.net/archives/2011/trigonometria-sin-cos-tan-30-45-60/#comments</comments>
		<pubDate>Wed, 20 Jul 2011 02:22:58 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[maths]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1648</guid>
		<description><![CDATA[Com trobar els valors? Taula resum &#160; 30º 45º 60º sin cos tg Related posts: Apunts de Càlcul: Nombres reals i nombres complexos 1. Nombres reals Naturals Propietats: Propietats: Enters La suma també...]]></description>
			<content:encoded><![CDATA[<table border="0" style="border: 0; width: 100%;">
<tr>
<td style="border: 0; vertical-align: top;">
<h5>Com trobar els valors?</h5>
<table border="0">
<tr>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/07/Triangle-amb-un-angle-de-45-graus.png"><img src="http://bloc.eurion.net/wp-content/uploads/2011/07/Triangle-amb-un-angle-de-45-graus.png" alt="" title="Triangle amb un angle de 45 graus" width="250" height="191" class="aligncenter size-full wp-image-1688" /></a></td>
<td>\(<br />
    \begin{array}{ll}<br />
      \sin45º &#038; =\frac{1}{\sqrt{2}}=\frac{\sqrt{2}}{2} \\<br />
      \cos45º &#038; =\frac{1}{\sqrt{2}}=\frac{\sqrt{2}}{2} \\<br />
      \tan45º &#038; =1 \\<br />
    \end{array}\)
  </td>
</tr>
<tr>
<td rowspan="2"><a href="http://bloc.eurion.net/wp-content/uploads/2011/07/Triangle-amb-angles-de-30-i-60-graus.png"><img src="http://bloc.eurion.net/wp-content/uploads/2011/07/Triangle-amb-angles-de-30-i-60-graus-300x218.png" alt="" title="Triangle amb angles de 30 i 60 graus" width="300" height="218" class="aligncenter size-medium wp-image-1687" /></a></td>
<td>\(<br />
    \begin{array}{ll}<br />
      \sin30º &#038; =\frac{1}{2} \\<br />
      \cos30º &#038; =\frac{\sqrt{3}}{2} \\<br />
      \tan30º &#038; =\frac{1}{\sqrt{3}} \\<br />
    \end{array}\)
  </td>
</tr>
<tr>
<td>\(<br />
    \begin{array}{ll}<br />
      \sin60º &#038; =\frac{\sqrt{3}}{2} \\<br />
      \cos60º &#038; =\frac{1}{2} \\<br />
      \tan60º &#038; =\sqrt{3} \\<br />
    \end{array}\)
  </td>
</tr>
</table>
</td>
<td style="border: 0; vertical-align: top;">
<h5>Taula resum</h5>
<table border="0" style="font-size: large;">
<tr>
<th>&nbsp;</th>
<th>30º</th>
<th>45º</th>
<th>60º</th>
</tr>
<tr>
<th>sin</th>
<td style="text-align: center;">\(1/2\)</td>
<td style="text-align: center;">\(\sqrt{2}/2\)</td>
<td style="text-align: center;">\(\sqrt{3}/2\)</td>
</tr>
<tr>
<th>cos</th>
<td style="text-align: center;">\(\sqrt{3}/2\)</td>
<td style="text-align: center;">\(\sqrt{2}/2\)</td>
<td style="text-align: center;">\(1/2\)</td>
</tr>
<tr>
<th>tg</th>
<td style="text-align: center;">\(\sqrt{3}/3\)</td>
<td style="text-align: center;">\(1\)</td>
<td style="text-align: center;">\(\sqrt{3}\)</td>
</tr>
</table>
</td>
</tr>
</table>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/calcul-nombres-reals-i-complexos/' rel='bookmark' title='Apunts de Càlcul: Nombres reals i nombres complexos'>Apunts de Càlcul: Nombres reals i nombres complexos</a> <small>1. Nombres reals Naturals Propietats: Propietats: Enters La suma també...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/trigonometria-sin-cos-tan-30-45-60/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apunts de Càlcul: Funcions d&#8217;una variable</title>
		<link>http://bloc.eurion.net/archives/2011/calcul-funcions-duna-variable/</link>
		<comments>http://bloc.eurion.net/archives/2011/calcul-funcions-duna-variable/#comments</comments>
		<pubDate>Wed, 20 Jul 2011 01:53:38 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[calculus]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1557</guid>
		<description><![CDATA[Introducció Considerem una funció real de variable real tal que existeix com a màxim un . Definim: Definim el domini d&#8217;una funció: I el recorregut d&#8217;una funció: També: &#160; Exemple Tipus de funcions Una funció : és parella és imparella és periòdica de període és creixent (no decreixent) és estrictament creixent és decreixent és estrictament [...]]]></description>
			<content:encoded><![CDATA[<h5>Introducció</h5>
<p>Considerem una funció real de variable real \(f: A \in \mathbb{R} \rightarrow \mathbb{R}\) tal que \(\forall x \in A\) existeix com a màxim un \(y \in \mathbb{R} : y=f(x)\). Definim:</p>
<p>Definim el <a href="http://ca.wikipedia.org/wiki/Domini_(matem%C3%A0tiques)">domini</a> d&#8217;una funció:<br />
\(\operatorname{Dom} f = \left\{x \in \mathbb{R} / \exists f(x) \in \mathbb{R}\right\} = \left\{x \in \mathbb{R} / \exists y \in \mathbb{R} / y=f(x)\right\}\)</p>
<p>I el <a href="http://ca.wikipedia.org/wiki/Recorregut_(matem%C3%A0tiques)">recorregut</a> d&#8217;una funció:<br />
\(\operatorname{Im} f = \left\{f(x) / x \in \operatorname{Dom} f\right\} = \left\{y \in \mathbb{R} / \exists x \in \operatorname{Dom} f / y=f(x)\right\}\)</p>
<p>També: \(\operatorname{Graf}(f) = \left\{(x,y) / x \in \operatorname{Dom} f\right\}\)&nbsp;</p>
<p><strong>Exemple</strong></p>
<table border="0" style="margin-left: 50px;">
<tr>
<td>
  \(\begin{array}{ll}f: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto f(x)=|x|\end{array}\)
</td>
<td>
 \(\operatorname{Dom f} = \mathbb{R}\)<br />
 \(\operatorname{Im f} = \mathbb{R^+} \cup \{0\} = [0, +\infty)\)<br />
 \(\operatorname{Graf(f)} = \left\{(x,x) / x \ge 0\right\} \cup \left\{(x,-x) / x < 0\right\}\)
</td>
</td>
</tr>
</table>
<h5>Tipus de funcions</h5>
<p>Una funció \(\begin{array}{ll}f: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto f(x)\end{array}\):</p>
<p><span id="more-1557"></span></p>
<ol>
<li>és <strong>parella</strong> \(\Leftrightarrow \forall x \in \operatorname{Dom} f, f(-x) = f(x)\)</li>
<li>és <strong>imparella</strong> \(\Leftrightarrow \forall x \in \operatorname{Dom} f, f(-x) = -f(x) \)</li>
<li>és <strong>periòdica de període \(w \in \mathbb{R}\)</strong> \(\Leftrightarrow \forall x \in \operatorname{Dom} f, \begin{cases}f(x+w) = f(x) \\ \forall k \in \mathbb{Z}, f(x+kw)=f(x)\end{cases}\)</li>
<li>és <strong>creixent</strong> (no decreixent) \(\Leftrightarrow \forall x,y \in \operatorname{Dom} f, x < y \Rightarrow f(x) \le f(y) \)</li>
</li>
<li>és <strong>estrictament creixent</strong> \(\Leftrightarrow \forall x, y \in \operatorname{Dom} f, x < y \Rightarrow f(x) < f(y) \)</li>
</li>
<li>és <strong>decreixent</strong> \(\Leftrightarrow \forall x,y \in \operatorname{Dom} f, x < y \Rightarrow f(x) \ge f(y)\)</li>
</li>
<li>és <strong>estrictament decreixent</strong> \(\Leftrightarrow \forall x,x \in \operatorname{Dom} f, x < y \Rightarrow f(x) > f(y)\)</li>
<li>està <strong>acotada superiorment</strong> \(\Leftrightarrow \exists k \in \mathbb{R} / \forall x \in \operatorname{Dom} f, f(x) \le k\)</li>
<li>està <strong>acotada inferiorment</strong> \(\Leftrightarrow \exists m \in \mathbb{R} / \forall x \in \operatorname{Dom} f, f(x) \ge m\)</li>
<li>està <strong>acotada</strong> \(\Leftrightarrow \exists k \in \mathbb{R} / \forall x \in \operatorname{Dom} f, |f(x)| \le k\)</li>
<li>és <strong>injectiva</strong> \(\Leftrightarrow \forall x_1, x_2 \in \operatorname{Dom} f, x_1 \ne x_2 \Rightarrow f(x_1) \ne f(x_2)\)</li>
<li>és <strong>exhaustiva</strong> \(\Leftrightarrow \begin{array}{l}\operatorname{Im} f = \mathbb{R} \\ \forall y \in \mathbb{R}, \exists x \in \operatorname{Dom} f / y = f(x)\end{array}\)</li>
<li>és <strong>bijectiva</strong> \(\Leftrightarrow\) és injectiva i exhaustiva (\(\forall y \in \mathbb{R}, \exists!x / f(x)=y\))</li>
</ol>
<h5>Operacions amb funcions</h5>
<table border="0" class="noborder">
<tr>
<td>
\(<br />
\begin{cases}<br />
 \begin{array}{ll}f: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto f(x)\end{array} \\<br />
 \begin{array}{ll}g: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto g(x)\end{array} \\<br />
 \lambda \in \mathbb{R}<br />
\end{cases}<br />
\)
</td>
<td>
\(<br />
\begin{array}{l}<br />
 \begin{array}{ll}f+g: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto (f+g)(x)=f(x)+g(x)\end{array} \\<br />
 \begin{array}{ll}f/g: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto (\frac{f}{g})(x)=\frac{f(x)}{g(x)} \text{ si } g(x) \ne 0\end{array} \\<br />
 \begin{array}{ll}\lambda f: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto (\lambda f)(x)=\lambda\cdot f(x)\end{array} \\<br />
\end{array}<br />
\)
</td>
</tr>
</table>
<h5>Composició de funcions</h5>
<p>\(f\circ g \;\;\;\;\;\; \begin{array}{l}\mathbb{R} \rightarrow \mathbb{R} \\ x \mapsto (f\circ g)(x)=f(g(x))\end{array}\)&nbsp;</p>
<h5>Funció inversa</h5>
<table border="0" class="noborder" style="margin-top: -10px;">
<tr>
<td>
 \(\begin{array}{ll}f: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto f(x)\end{array}\)
</td>
<td>
 Funció injectiva \(\Rightarrow\) la seva funció inversa és \(\begin{array}{ll}f^{-1}: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto f^{-1}(x)\end{array}\) \(f^{-1}\circ f = f \circ f^{-1} = I\) &nbsp; &nbsp; &nbsp; &nbsp; \(\begin{cases}\forall x \in \operatorname{Dom} f^{-1} &#038; f(f^{-1}(x))=x \\ \forall x \in \operatorname{Dom} f &#038; f^{-1}(f(x))=x\end{cases}\)
</td>
</tr>
</table>
<h5>Asímptotes</h5>
\(\begin{array}{ll}f: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto f(x)\end{array}\)
<table border="0">
<tr>
<td>\(x=a\) és una <strong>asímptota vertical</strong> de la funció \(f \Leftrightarrow \lim_{x \to a} (x) = \begin{cases}+\infty \\ -\infty \\ \infty\end{cases}\)</td>
<td><img src="http://bloc.eurion.net/wp-content/uploads/2011/07/Asímptota-vertical.png" alt="" title="Asímptota vertical" width="111" height="94" class="aligncenter size-full wp-image-1633" /></td>
</tr>
<tr>
<td style="min-width: 300px;">\(x=b\) és una <strong>asímptota horizontal</strong>&#8230;</p>
<ul>
<li><strong>per la dreta</strong> \(\Leftrightarrow \lim_{x \to +\infty} f(x) = b\)</li>
<li><strong>per l&#8217;esquerra</strong> \(\Leftrightarrow \lim_{x \to -\infty} f(x) = b\)</li>
</ul>
</td>
<td><img src="http://bloc.eurion.net/wp-content/uploads/2011/07/Asímptota-horizontal.png" alt="" title="Asímptota horizontal" width="95" height="74" class="aligncenter size-full wp-image-1616" /></td>
</tr>
<tr>
<td colspan="2">\(y=mx+n\) és una <strong>asímptota oblíqua</strong>&#8230;</p>
<ul>
<li><strong>per la dreta</strong> d&#8217;\(y=f(x) \Leftrightarrow m=\lim_{x \to +\infty} \frac{f(x)}{x}\) i \(m=\lim_{x \to +\infty}(f(x)-mx)\)</li>
<li><strong>per l&#8217;esquerra</strong> (igual que per la dreta però amb \(-\infty\))</li>
</ul>
</td>
</tr>
</table>
<h5>Continuïtat</h5>
<table border="0" class="noborder">
<tr>
<td style="vertical-align: top;">\(\begin{array}{l}\begin{array}{l?}f: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto f(x)\end{array} \\ a \in \mathbb{R}\end{array}\)</td>
<td style="vertical-align: top;">
<p>\(f\) és <strong>contínua en \(a\)</strong> \(\Leftrightarrow \exists f(a) \land \exists \lim_{x \to a} f(x) \land \lim_{x \to a} f(x) = f(a)\) (amb \(a \in \operatorname{Dom}f\)).</p>
<p>\(f\) és <strong>contínua en \(A\)</strong> \(\Leftrightarrow f\) és contínua en \(a\), \(\forall a \in A\).</p>
</td>
</tr>
</table>
<h6>Tipus de punts de discontinuïtat d&#8217;una funció</h6>
<table border="0">
<tr>
<td>
<p>\(a\) és un punt de <strong>discontinuïtat evitable</strong> d&#8217;\(f\) \(\Leftrightarrow \exists \lim_{x \to a} f(x) \land (\nexists f(a) \lor f(a) \ne \lim_{x \to a} f(x))\).</p>
<p>Per evitar aquest tipus de discontinuïtat podem redefinir la funció: \(F(x)=\begin{cases}f(x) &#038; x \ne a \\ \lim f(x) &#038; x=a\end{cases}\)</p>
</td>
</tr>
<tr>
<td>
<p>Si \(\nexists \lim_{x \to a}f(x) \in \mathbb{R} \Rightarrow a\) és un punt de <strong> discontinuïtat essencial</strong>.</p>
<p style="margin-left: 50px;">Si \(\lim_{x \to a} f(x) = \begin{cases}+\infty \\ -\infty \\ \infty\end{cases} \Rightarrow a\) és un punt de <strong>discontinuïtat asimptòtica</strong> o <strong>de 2a espècia.</strong></p>
<p style="margin-left: 50px;">Si \(\begin{cases}\lim_{x\to a^{-}} f(x) \in \mathbb{R} \\ \land \\ \lim{x \to a^{+}} f(x) \in \mathbb{R} \\ \land \\ \lim_{x \to a^{-}} f(x) \ne \lim_{x \to a^{+}} f(x)\end{cases} \Rightarrow a\) és un punt de discontinuïtat <strong>de salt finit</strong>.</p>
</td>
</tr>
</table>
<h5>Derivabilitat</h5>
<table border="0" class="noborder">
<tr>
<td style="vertical-align: top;">\(\begin{array}{l}\begin{array}{l?}f: &#038; \mathbb{R} \rightarrow \mathbb{R} \\ &#038; x \mapsto f(x)\end{array} \\ a \in \operatorname{Dom}f\end{array}\)</td>
<td style="vertical-align: top;">
<p>\(f\) és derivable en \(a\) si \(\exists \lim_{x \to a} \frac{f(x)-f(a)}{x-a} \in \mathbb{R}\). Aquest és igual a \(\lim_{h \to 0} \frac{f(a+h) &#8211; f(a)}{h}\) = \(f&#8217;(a)\) = pendent de la recta tangent a la curva \(y = f(x)\) en el punt d&#8217;abscissa \(a\), \((a, f(a))\).</p>
</td>
</tr>
<tr>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/07/Derivabilitat.png"><img src="http://bloc.eurion.net/wp-content/uploads/2011/07/Derivabilitat-300x225.png" alt="" title="Derivabilitat" width="300" height="225" class="aligncenter size-medium wp-image-1694" /></a></td>
<td>Recta tangent a \(y=f(x)\) on el punt d&#8217;\(x=a\): \(y=f(a)+f&#8217;(a)(x-a)\).</td>
</tr>
</table>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/calcul-nombres-reals-i-complexos/' rel='bookmark' title='Apunts de Càlcul: Nombres reals i nombres complexos'>Apunts de Càlcul: Nombres reals i nombres complexos</a> <small>1. Nombres reals Naturals Propietats: Propietats: Enters La suma també...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-calcul-cost-algorismes/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs'>Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs</a> <small>Introducci&oacute; Els algorismes s&oacute;n per tot arreu i per aix&ograve;...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/computacio-teoria-de-llenguatges/' rel='bookmark' title='Apunts de Teoria de la Computació: Teoria de llenguatges'>Apunts de Teoria de la Computació: Teoria de llenguatges</a> <small>Un alfabet () és un conjunt finit d&#8217;elements (símbols), habitualment...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/calcul-funcions-duna-variable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apunts de Càlcul: Nombres reals i nombres complexos</title>
		<link>http://bloc.eurion.net/archives/2011/calcul-nombres-reals-i-complexos/</link>
		<comments>http://bloc.eurion.net/archives/2011/calcul-nombres-reals-i-complexos/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 01:09:47 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[calculus]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[maths]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1424</guid>
		<description><![CDATA[1. Nombres reals Naturals Propietats: Propietats: Enters La suma també és una operació interna i té element neutre (0) i element oposat. El producte no canvia (és igual que amb els nombres naturals). Racionals La suma segueix igual que en el cas anterior (associativa, commutativa, element neutre, element oposat). El producte guanya l&#8217;element invers: Podem [...]]]></description>
			<content:encoded><![CDATA[<h4>1. Nombres reals</h4>
<p>
<strong>Naturals</strong> \(\mathbb{N}=\left\{1,2,3,4,&#8230;\right\}\)</p>
<div style="margin-left: 50px;">
\(<br />
\begin{array}{ll}+: &#038; \mathbb{N}\times\mathbb{N} \rightarrow \mathbb{N} \\ &#038; (n, m) \mapsto n+m\end{array}<br />
\)</p>
<p>Propietats: \(\begin{cases}<br />
associativa: &#038; a+(b+c) = (a+b)+c \\<br />
commutativa: &#038; a+b=b+a \;\;\;\;\;\; \forall a,b \in \mathbb{N}<br />
\end{cases}\)</p>
\(<br />
\begin{array}{ll}\cdot: &#038; \mathbb{N}\times\mathbb{N} \rightarrow \mathbb{N} \\ &#038; (n, m) \mapsto n\cdot m\end{array}<br />
\)
<p>Propietats: \(\begin{cases}<br />
associativa \\<br />
commutativa \\<br />
element\;neutre\;(1) \\<br />
distributiva\;respecte\;a\;la\;suma: &#038; a(b+c)=ab+ac<br />
\end{cases}\)
</p></div>
</p>
<p>
<strong>Enters</strong> \(\mathbb{Z}=\left\{&#8230;,-1,0,1,&#8230;\right\}\)</p>
<div style="margin-left: 50px;">
La suma també és una <a href="http://ca.wikipedia.org/wiki/Operaci%C3%B3_matem%C3%A0tica#Llei_de_composici.C3.B3_interna">operació interna</a> i té element neutre (0) i element oposat. El producte no canvia (és igual que amb els nombres naturals).
</div>
</p>
<p>
<strong>Racionals</strong> \(\mathbb{Q}=\left\{\frac{a}{b} | a,b \in \mathbb{Z}, b \ne 0\right\}\)</p>
<div style="margin-left: 50px;">
La suma segueix igual que en el cas anterior (associativa, commutativa, element neutre, element oposat).</p>
<p>El producte guanya l&#8217;element invers: \(\forall x \in \mathbb{Q}, x \ne 0, \exists \frac{1}{x} \in \mathbb{Q} \text{ tal que } x\cdot\frac{1}{x}=\frac{1}{x}\cdot{}x=1\)</p>
<p>Podem resumir-ho com a: \((\mathbb{Q}, +, \cdot)\) <a href="http://ca.wikipedia.org/wiki/Cos_(matem%C3%A0tiques)">cos commutatiu</a>.</p>
<p>A més, \(\mathbb{Q}\) té les propietats:</p>
<ol>
<li>donats 2 nombres racionals, existeixen infinits nombres entre ells (\(\mathbb{Q}\) és dens en \(\mathbb{R}\)).<br />
\(\forall p,q \in \mathbb{Q}, p \ne q \Rightarrow \exists\) infinits nombres racionals diferents entre \(p\) i \(q\).<br />
Demostració: Suposem \(p < q \Rightarrow p < \frac{p+q}{2} < q\).</li>
</li>
<li>\(q \in \mathbb{Q} \Rightarrow q\) admet una expressió decimal exacta o peròdica. Exemples:<br />
\(\frac{1}{4}=0.25\), \(\frac{1}{3}=0.\overline{3}\), \(\frac{23}{90}=mixte\).</li>
</ol>
</div>
<p><span id="more-1424"></span></p>
<p>
<strong>Irracionals</strong> \(\mathbb{I}=\mathbb{R}-\mathbb{Q}\)</p>
<div style="margin-left: 50px;">
Són el conjunt dels nombres amb expressió decimal que tenen infinites xifres decimals no periòdiques.</p>
<p>Exemples: \(\pi, \sqrt{2}, \sqrt{5}, e, 1.12131412345\ldots, etc.\).
</p></div>
</p>
<p>
<strong>Reals</strong> \(\mathbb{R} = \mathbb{Q} \cup \left\{\mathbb{R}-\mathbb{Q}\right\}\)</p>
<div style="margin-left: 50px">
\((\mathbb{R}, +, \cdot)\) cos commutatiu ordenat (els nombres tenen ordre).
</div>
</p>
<h5>Relació d&#8217;ordre en \(\mathbb{R}\)</h5>
\(x, y \in \mathbb{R}: x \le y \Leftrightarrow y-x \ge 0\)
<p style="margin-top: 15px;">\(\begin{array}{ll}<br />
1.\; \forall x &#038; x \le x \\<br />
2.\; \forall x,y &#038; (x \le y \land y \le x) \Rightarrow x=y \\<br />
3.\; \forall x,y,z &#038; \begin{cases}x \le y \\ y \le z\end{cases} \Rightarrow x \le z \\<br />
4.\; \forall x,y &#038; x \le y \lor y \le x \\<br />
5.\; \forall x,y,z \in \mathbb{R} &#038; x \le y \Rightarrow x+z \le y+z \\<br />
6.\; \forall x,y \in \mathbb{R}, \forall z \in \mathbb{R}, z \ge 0 &#038; x \le y \Rightarrow xz \le yz \\<br />
7.\; \forall x,y \in \mathbb{R}, \forall z \in \mathbb{R}, z < 0 &#038; x \le y \Rightarrow xz \ge yz \\<br />
8.\; x < y \Leftrightarrow \begin{cases}x \le y \\ x \ne y\end{cases}<br />
\end{array}\)</p>
<h5 style="margin-top: 20px;">Elements notables d&#8217;un conjunt respecte de la \(\le\)</h5>
<table border="0">
<tr>
<td rowspan="2">\(\begin{cases}A \subset \mathbb{R} \\ x \in \mathbb{R}\end{cases}\)</td>
<td>x és una cota inferior d&#8217;A \(\Leftrightarrow\) \(x \le a\;\;\;\;\;\forall a \in A\)</td>
</tr>
<tr>
<td>x és una cota superior d&#8217;A \(\Leftrightarrow\) \(x \ge a\;\;\;\;\;\forall a \in A\)</td>
</tr>
</table>
<p>A està acotat inferiorment \(\Leftrightarrow \exists x \in \mathbb{R}\) / \(x\)  és cota inferior d&#8217;A.<br />
A està acotat superiorment \(\Leftrightarrow \exists x \in \mathbb{R}\) / \(x\) és cota superior d&#8217;A.<br />
A està acotat \(\Leftrightarrow\) A està acotat superiorment i inferior.</p>
<p>x és el <em>ínfim</em> d&#8217;A \(\Leftrightarrow\) x és la major de les cotes inferiors d&#8217;A \(\to x = \inf A\).<br />
x és el <em>suprem</em> d&#8217;A \(\Leftrightarrow\) x és la menor de les cotes superior d&#8217;A \(\to x = \sup A\).</p>
<div style="margin-left: 50px;">
si \(\inf A \in A \Rightarrow \inf A = \min A\)<br />
si \(\sup A \in A \Rightarrow \sup A = \max A\)
</div>
<p><strong>Teorema de l&#8217;extrem</strong> (també axioma del suprem) \(\leftarrow \begin{cases}es\;compleix\;en\;\mathbb{R} \\ no\;es\;\;compleix\;en\;\mathbb{Q}\end{cases}\)</p>
<p>\(A \subseteq \mathbb{R}, A\) acotat superiorment \(\Rightarrow \exists x \in \mathbb{R}\) / \(x=sup A\)<br />
\(A \subseteq \mathbb{R}, A\) acotat inferiorment \(\Rightarrow \exists x \in \mathbb{R}\) / \(x=inf A\)</p>
<h5 style="margin-top: 20px;">Valor absolut</h5>
\(x \in \mathbb{R}\;\;\;\;\;\;|x| = \begin{cases}x &#038; x \ge 0 \\ -x &#038; x < 0\end{cases}\)
<p>Propietats:</p>
<p style="margin-top: 15px;">\(\begin{array}{ll}<br />
1.\; \forall x &#038; |x| \ge 0 \\<br />
2.\; &#038; |x| = 0 \Rightarrow x = 0 \\<br />
3.\; \forall x,y &#038; |x+y| \le |x| + |y| \\<br />
4.\; \forall x,y &#038; |x\cdot y| = |x| \cdot |y| \\<br />
5.\; a > 0 &#038; |x| < a \Leftrightarrow -a < x < a \Leftrightarrow x \in (-a, a) \\<br />
6.\; a > 0 &#038; |x| > a \Leftrightarrow x \le -a \lor x > a<br />
\end{array}\)</p>
<p><!-- -------------------------------------------------- --></p>
<hr />
<h4 style="margin-top: 25px;">2. Nombres complexos</h4>
<p>La «unitat imaginària» és \(\sqrt{-1}=i\).</p>
<p>Els <strong>nombres complexos</strong> són els nombres \(a+bi\), amb \(a,b \in \mathbb{R}\).</p>
<p>Conjunt dels nombres complexos: \(\mathbb{C} = \left\{a+bi | a,b \in \mathbb{R^2}\right\}\).</p>
<p>Donat \(z=a+bi \; \begin{cases}a = part\;real\;del\;nombre\;complex\;z \\ b=part\;imaginària\;del\;nombre\;complex\end{cases}\)</p>
<p>Donat \(z=a+bi\), diem que el <em>conjugat</em> de \(z\) és \(\overline{z}=a-bi\).</p>
<p>En \(\mathbb{C}\), \(ax^2+bx+c=0\) amb \(a,b,c \in \mathbb{R}\), sempre té solució en \(\mathbb{C}\). Exemple:</p>
<p style="margin-left: 50px;">
\(x^2-4x+8=0 \Rightarrow x = \frac{4\pm\sqrt{16-32}}{2} = \frac{4 \pm \sqrt{-16}}{2} = \frac{4\pm4i}{2} = \begin{cases}2+2i \\ 2-2i\end{cases}\)<br />
<small>(Recorda: \(\sqrt{ab}=\sqrt{a}\sqrt{b}\))</small>
</p>
<h5>Operacions</h5>
<p><strong>Suma</strong></p>
<p style="margin-left: 50px;">
\(\begin{cases}z_{1}=a+bi \\ z_{2}=c+di\end{cases} \;\;\;\;\;\; z_1+z_2=(a+c)+(b+d)i\)
</p>
<p><strong>Producte</strong></p>
<p style="margin-left: 50px;">
\(z_1z_2 = (a+bi)(c+di) = ac + adi + bci + bdi^2 = (ac-bd)+(ad+bi)i\)<br />
<small>(Recorda: \(i^2=-1\))</small>
</p>
<p>\((\mathbb{C}, +, \cdot)\) és un cos commutatiu.</p>
<p>L&#8217;<strong>invers</strong> de \(z=a+bi \ne 0\) és \(\frac{1}{z}=\frac{1}{a+bi}=\frac{(a-bi)}{(a+bi)(a-bi)}=\frac{a-bi}{a^2-(bi)^2}=\frac{a-bi}{a^2-b^2i^2}=\) \(\frac{a-bi}{a^2+b^2}=\frac{a}{a^2+b^2}-\frac{b}{a^2+b^2}i\)</p>
<p><strong>Quocient</strong></p>
<p style="margin-left: 50px;">
\(\frac{z_1}{z_2}=\frac{a+bi}{c+di}=\frac{(a+bi)(c-di)}{(c+di)(c-di)}=\frac{ac+bd}{c^2+d^2}+\frac{bc-ad}{c^2+d^2}i\)
</p>
<p>&nbsp;</p>
<h5>Mòdul d&#8217;un nombre complex</h5>
<p style="margin-left: 50px;">
\(z=a+bi \rightarrow |z|=\sqrt{a^2+b^2}=\sqrt{z\cdot\overline{z}}\)</p>
<p>Propietats:
</p>
\(\begin{cases}<br />
1.\; |z| \ge 0 &#038; \forall z \in \mathbb{C} \\<br />
2.\; |z| = 0 &#038; z = 0 = 0+0i \\<br />
3.\; \forall z_1, z_2 \in \mathbb{C} &#038; |z_1+z_2| \le |z_1|+|z_2| \\<br />
4.\; \forall z_1, z_2 \in \mathbb{C} &#038; |z_1\cdot z_2| = |z_1|\cdot|z_2| \\<br />
5.\; &#038; z \in \mathbb{R} \Leftrightarrow b=0 \Rightarrow |z| \text{ (mòdul)} = |z| \text{ (abs)}<br />
\end{cases}\)
<p>&nbsp;</p>
<h5>Argument d&#8217;un nombre complex</h5>
<p style="margin-left: 50px;">
<table border="0">
<tr>
<td>\(z=a+bi \rightarrow \arg(z)=\) angle que forma en \(\mathbb{R^2}\) el vector origen (0,0) i final (a,b) amb el semieix \(\vec{O_x^+}\).</td>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/07/Nombres_complexos.png"><img src="http://bloc.eurion.net/wp-content/uploads/2011/07/Nombres_complexos.png" alt="" title="Nombres_complexos" width="295" height="247" class="aligncenter size-full wp-image-1544" /></a><br />(Els signes d&#8217;<strong>a</strong> i <strong>b</strong> determinen el quadrant.)</td>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/07/Quadrants.png"><img src="http://bloc.eurion.net/wp-content/uploads/2011/07/Quadrants.png" alt="" title="Quadrants" width="195" height="195" class="aligncenter size-full wp-image-1545" /></a></td>
</tr>
</table>
<p>&nbsp;</p>
<h5>Com calcular la part real i la part imaginària sabent \(|z|\) i \(\arg(z)\)?</h5>
<p style="margin-left: 50px;">
\(\sin \alpha = \frac{b}{|z|} \rightarrow b=|z|\sin(\arg(z))\)<br />
\(\cos \alpha = \frac{a}{|z|} \rightarrow a=|z|\cos(\arg(z))\)
</p>
<h5>Representacions dels nombres complexos</h5>
<p>Amb \(z \in \mathbb{Z}\), la forma \(z=a+bi\) és anomenada la <strong>forma binòmica</strong> del nombre complex \(z\).</p>
<p>També podem expressar \(z\) per mitjà de \(|z|\) i \(\arg(z)=\alpha\) de la següent forma: \(z = |z|\cos(\arg(z)) + |z|\sin(\arg(z))i = |z|(\cos\alpha+i\sin\alpha)\). Aquesta representació s&#8217;anomena <strong>forma trigonomètrica</strong> de \(z\).</p>
<p>Finalment, també utilitzem la <strong>forma polar</strong>: \(z=|z|_{\arg(z)}=r_{\alpha}\)&nbsp;</p>
<table border="0" style="margin-left: 50px;">
<tr>
<th colspan="2"><strong>Exemples:</strong></th>
</tr>
<tr>
<td>\(z=1+i \rightarrow\)</td>
<td>\(\left | \begin{array}{l}<br />
  |z|=\sqrt{1^2+1^2}=\sqrt{2} \\<br />
  \arg(z)=\arctan\frac{1}{1}=\arctan 1=\frac{\pi}{4} \\<br />
  z=\sqrt{2}(\cos\frac{\pi}{4}+i\sin\frac{\pi}{4})=\sqrt{2}(\frac{\sqrt{2}}{2}+i\frac{\sqrt{2}}{2}) \\<br />
  z=\sqrt{2}_{\frac{\pi}{4}}<br />
\end{array} \right .\)</td>
</tr>
<tr>
<td>\(z=-1-i \rightarrow\)</td>
<td>\(\left | \begin{array}{l}<br />
  |z|=\sqrt{2} \\<br />
  \arg(z)=\arctan\frac{-1}{-1}=\arctan 1=\frac{5\pi}{4} \\<br />
  z=\sqrt{2}(\cos\frac{5\pi}{4}+i\sin\frac{5\pi}{4})=\sqrt{2}(-\cos\frac{\pi}{4}-i\sin\frac{\pi}{4}) \\<br />
  z=\sqrt{2}_{\frac{5\pi}{4}}<br />
\end{array} \right .\)</td>
</tr>
<tr>
<td>\(z=1-i \rightarrow\)</td>
<td>\(\begin{array}{cc}|z|=\sqrt{2} &#038; \arg(z)=\arctan\frac{1}{-1}=\arctan -1=\frac{7\pi}{4}\end{array}\)</td>
</tr>
</table>
<p><strong>Representació gràfica</strong> dels nombres complexos en el pla complex:<br />
<a href="http://bloc.eurion.net/wp-content/uploads/2011/07/Representació-gràfica-dels-nombres-complexos.png"><img src="http://bloc.eurion.net/wp-content/uploads/2011/07/Representació-gràfica-dels-nombres-complexos.png" alt="" title="Representació gràfica dels nombres complexos" width="415" height="183" class="aligncenter size-full wp-image-1549" /></a></p>
<h5>Operacions en forma polar</h5>
<table border="0">
<tr>
<td rowspan="4">\(\begin{cases}z_1=r_{\alpha} \\ z_2=s_{\beta}\end{cases}\)</td>
<td colspan="2"><em>(No es pot sumar ni restar!)</em></td>
</tr>
<tr>
<td><strong>producte:</strong> \(z_1z_2=(r\cdot s)_{\alpha+\beta}\)</td>
<td><strong>potència:</strong> \((z_1)^n=(r^n)_{n\cdot\alpha}\)</td>
</tr>
<tr>
<td><strong>quocient:</strong> \(\frac{z_1}{z_2}=(\frac{r}{s})_{\alpha-\beta}\)</td>
<td><strong>arrel:</strong> \(\sqrt[n]{z_1}=<br />
    \begin{cases}<br />
      \sqrt[n]{r_{\frac{\alpha}{n}}} \\<br />
      \sqrt[n]{r_{\frac{\alpha+2\pi}{n}}} \\<br />
      &#8230; \\<br />
      \sqrt[n]{r_{\frac{\alpha+(n-1)2\pi}{n}}}<br />
    \end{cases}\)</td>
</tr>
<tr>
<td colspan="2"><strong>igualtat:</strong> \(r_\alpha=s_\beta \Leftrightarrow r=s \land \alpha-\beta=2k\pi, k \in \mathbb{Z}\)</td>
</tr>
</table>
<p>Si \(r=1\), per la fórmula de la potència: \((1_\alpha)^n=1_{n\alpha}\). Desenvolupant aquesta igualtat obtenim: \((\cos\alpha + i\sin\alpha)^n = (cos(n\alpha)+i\sin(n\alpha))\), la <a href="http://ca.wikipedia.org/wiki/F%C3%B3rmula_de_De_Moivre">fórmula de Moivre</a>.</p>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/calcul-funcions-duna-variable/' rel='bookmark' title='Apunts de Càlcul: Funcions d&#8217;una variable'>Apunts de Càlcul: Funcions d&#8217;una variable</a> <small>Introducció Considerem una funció real de variable real tal que...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-calcul-cost-algorismes/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs'>Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs</a> <small>Introducci&oacute; Els algorismes s&oacute;n per tot arreu i per aix&ograve;...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-dividir-i-vencer/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer'>Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer</a> <small>Introducci&oacute; L&#39;esquema de programaci&oacute; de dividir i v&egrave;ncer &eacute;s una...</small></li>
</ol></p> <p><a href="http://bloc.eurion.net/?flattrss_redirect&amp;id=1424&amp;md5=e7a8fc19e1a5499d3e8e25c2cc5675be" title="Flattr" target="_blank"><img src="http://bloc.eurion.net/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/calcul-nombres-reals-i-complexos/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Breu introducció al sistema de control de versions Bazaar</title>
		<link>http://bloc.eurion.net/archives/2011/introduccio-al-bzr/</link>
		<comments>http://bloc.eurion.net/archives/2011/introduccio-al-bzr/#comments</comments>
		<pubDate>Tue, 17 May 2011 16:49:03 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Planet Ubuntu.cat]]></category>
		<category><![CDATA[bzr]]></category>
		<category><![CDATA[desenvolupament]]></category>
		<category><![CDATA[vcs]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1389</guid>
		<description><![CDATA[Introducci&#243; A l&#39;hora de desenvolupar aplicacions inform&#224;tiques en grup &#233;s molt important disposar d&#39;un sistema de control de versions (VCS,&#160;version control system). Explicat molt breument, els VCS s&#243;n&#160;eines de desenvolupament que permeten desar captures del codi font (revisions) creant tot un historial de canvis a mida que avan&#231;a el desenvolupament del programa; a m&#233;s, permeten [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introducci&oacute;<br />
	</strong></p>
<p>A l&#39;hora de desenvolupar aplicacions inform&agrave;tiques en grup &eacute;s molt important disposar d&#39;un sistema de control de versions (<strong>VCS</strong>,&nbsp;<em>version control system</em>). Explicat molt breument, els VCS s&oacute;n&nbsp;eines de desenvolupament que permeten desar captures del codi font (<em>revisions</em>) creant tot un historial de canvis a mida que avan&ccedil;a el desenvolupament del programa; a m&eacute;s, permeten compartir aquestes captures amb els companys de treball i normalment tenen capacitats per resoldre conflictes entre revisions creades en para?lel per diferents persones.</p>
<p>Un VCS potent utilitzat correctament pot incrementar la productivitat de forma dr&agrave;stica, al reduir problemes de coordinaci&oacute; facilitant que diferents desenvolupadors puguin compartir f&agrave;cilment les &uacute;ltimes versions de la seva feina i que&nbsp;m&eacute;s d&#39;una persona pugui fer canvis simultanis a un mateix conjunt de fitxers minimitzant els possibles conflictes resultants.</p>
<p>Hi ha un gran ventall de sistemes de control de versions disponibles, dels quals el m&eacute;s conegut &eacute;s segurament el <strong><a href="http://subversion.apache.org/">Subversion</a></strong>. Aquest, per&ograve;, permet &uacute;nicament un model <a href="http://en.wikipedia.org/wiki/Distributed_revision_control#Distributed_vs._centralized">centralitzat</a>&nbsp;i en general &eacute;s bastant limitat. Personalment prefereixo sistemes com ara el <a href="http://bazaar.canonical.com/en/"><strong>Bazaar</strong></a>&nbsp;(<em>bzr</em>). (El <a href="http://ca.wikipedia.org/wiki/Git"><strong>Git</strong></a> &eacute;s encara m&eacute;s potent, per&ograve; &eacute;s molt m&eacute;s dif&iacute;cil d&#39;aprendre a utilitzar, pel qual en aquest apunt em centrar&eacute; en el Bazaar; tamb&eacute; hi ha altres alternatives, com ara el <a href="http://ca.wikipedia.org/wiki/Mercurial">Mercurial</a>,&nbsp;per&ograve; no estic familiaritzat amb aquestes).</p>
<p><strong>Instal&middot;laci&oacute;</strong></p>
<p>En sistemes com ara l&#39;Ubuntu o Debian est&agrave; disponible en un paquet anomenat &laquo;bzr&raquo; i segurament el mateix sigui cert per a altres distribucions de GNU/Linux. Si feu servir un altre sistema operatiu podeu baixar-lo de&nbsp;<a href="http://wiki.bazaar.canonical.com/Download">bazaar.canonical.com</a>.</p>
<p>Com a nota al marge, el Bazaar tamb&eacute; disposa d&#39;una interf&iacute;cie gr&agrave;fica (<a href="http://doc.bazaar.canonical.com/explorer/en/">Bazaar Explorer</a>), per&ograve; ja que aquest apunt l&#39;escric orientat a desenvolupadors nom&eacute;s explicar&eacute; el seu &uacute;s des de la l&iacute;nia d&#39;ordres.</p>
<p><strong>Configuraci&oacute;</strong></p>
<p>Abans de poder fer operacions d&#39;escriptura cal que digueu al Bazaar com us voleu identificar. Podeu fer-ho de la seg&uuml;ent forma:</p>
<pre>bzr whoami &quot;<em>Nom Cognom</em> &lt;<em>email@domini.tld</em>&gt;&quot;</pre>
<p>En cas que feu servir el portal <a href="https://launchpad.net/">Launchpad</a>, tamb&eacute; podeu habilitat la integraci&oacute; amb aquest (si no coneixeu el Launchpad, podeu ignorar aix&ograve;):</p>
<pre>bzr launchpad-login <em>nom_usuari</em></pre>
<p><b>Primers passos</b></p>
<p>Imaginem que estem dins un directori &laquo;el-meu-projecte&raquo; on hi tenim un seguit de fitxers de codi (&laquo;main.c&raquo; i &laquo;utils.c&raquo;). Per comen&ccedil;ar a utilitzar el Bazaar amb aquest codi el primer que hem de fer &eacute;s crear una <em><strong>branca</strong></em>:</p>
<pre>bzr init</pre>
<p>Ara podem afegir-hi els fitxers que volem que controli:</p>
<pre>bzr add main.c utils.c</pre>
<p>i tot seguit podem crear una primera <em><strong>revisi&oacute;</strong></em> (una captura del contingut actual dels fitxers):</p>
<pre>bzr commit -m &quot;Primera revisi&oacute; del meu nou projecte...&quot;</pre>
<p>Un cop fet aix&ograve;, imaginem que acabem de fer uns canvis al fitxer <em>main.c</em>. Un cop comprovat que aquests funcionen correctament, procedirem a crear una segona revisi&oacute;:</p>
<p>bzr commit -m &quot;Aqu&iacute; aniria una descripci&oacute; dels &uacute;ltims canvis.&quot;</p>
<p>I ja tenim dues revisions en la nostra branca. Ara podem recuperar el llistat de canvis que hem fet amb:</p>
<pre>bzr log</pre>
<p>I veuriem alguna cosa com la seg&uuml;ents</p>
<pre>------------------------------------------------------------
<strong>revno: 2</strong>
committer: Nom Cognom &lt;email@domini.tld&gt;
branch nick: foo
timestamp: Tue 2011-05-17 18:19:48 +0200
message:
&nbsp;&nbsp;Alguns altres canvis que he fet...
------------------------------------------------------------
<strong>revno: 1</strong>
committer: Nom Cognom &lt;email@domini.tld&gt;
branch nick: projecte1
timestamp: Tue 2011-05-17 18:19:29 +0200
message:

&nbsp;&nbsp;Primera revisi&oacute; del meu nou projecte...
</pre>
<p>Si voleu analitzar en m&eacute;s detall una revisi&oacute;, podeu comparar dues (o m&eacute;s) revisions amb l&#39;ordre:</p>
<pre>bzr diff -r<strong>1</strong>..<strong>2</strong></pre>
<p>A m&eacute;s, quan arribeu a una versi&oacute; estable del vostre programa podeu marcar la revisi&oacute; actual amb una <em>etiqueta</em>, fent:</p>
<pre>bzr tag <em>nom-etiqueta</em></pre>
<p>Llavors podreu utilitzar &quot;tag:<em>nom-etiqueta</em>&quot; per referir-vos a aquella versi&oacute; en lloc d&#39;haver de consultar el n&uacute;mero de revisi&oacute; (<em>revno</em>).</p>
<p><strong>Compartint la branca amb altres</strong></p>
<p><meta content="text/html; charset=utf-8" http-equiv="content-type" /></p>
<p>Fins ara nom&eacute;s hem estat treballant en local (aix&ograve; &eacute;s possible ja que el Bazaar -al contrari de l&#39;SVN- &eacute;s un sistema distribu&iuml;t). Imaginem que ara voleu compartir el codi amb un company perqu&egrave; pugui ajudar amb el desenvolupament. Per aix&ograve; us caldr&agrave; disposar d&#39;un servidor (qualsevol ordinador accessible, en realitat) on els dos hi tingueu acc&eacute;s SFTP. Enviar-hi la vostra branca completa (amb totes les revisions) &eacute;s tan f&agrave;cil com:</p>
<pre>bzr push sftp://<em>el-meu-servidor</em>.<em>tld</em>/<em>directori</em>/<em>dest&iacute;</em>/<em>projecte1</em></pre>
<p>(Si m&eacute;s enll&agrave; de l&#39;SFTP tamb&eacute; teniu acc&eacute;s via SSH, i el servidor t&eacute; el <strong>bzr</strong>&nbsp;insta?lat, podeu utilitzar el mode de servidor inte?ligent amb &laquo;bzr+ssh://&raquo;. D&#39;altra banda, si el company/a no t&eacute; acc&eacute;s al servidor, sempre es pot posar la branca en un lloc accessible des de la web i llavors hi tindr&agrave; acc&eacute;s nom&eacute;s de lectura, via &laquo;http://&raquo;).</p>
<p>Per obtenir una c&ograve;pia de la branca, l&#39;altre persona pot fer:</p>
<pre>bzr branch&nbsp;sftp://<em>nom-d'usuari</em>@<em>el-meu-servidor</em>.<em>tld</em>/<em>directori</em>/<em>dest&iacute;</em>/<em>projecte1</em></pre>
<p>A partir d&#39;aqu&iacute;, els dos podeu fer &laquo;<em>bzr push</em>&raquo; per enviar els vostres canvis despr&eacute;s d&#39;un commit i &laquo;<em>bzr pull</em>&raquo; per recuperar canvis nous. En cas de produir-se un conflicte (el qual es produeix si es fa un <em>commit</em>&nbsp;sense tenir les &uacute;ltimes revisions de la branca del servidor) es pot arreglar amb &laquo;bzr merge&raquo;.</p>
<p>A m&eacute;s d&#39;aquests constants intercanvis, en qualsevol moment un dels dos pot decidir fer un <em>push</em>&nbsp;a una nova branca (per exemple, per desenvolupar alguna nova caracter&iacute;stica experimental) i quan la feina en aquesta estigui acabada, tornar-la a integrar (amb un <em>merge</em>) dins la branca principal (que, per cert, normalment s&#39;anomena&nbsp;<em>trunk</em>).</p>
<p><meta content="text/html; charset=utf-8" http-equiv="content-type" /></p>
<hr />
<p><small>
<a href="http://bloc.eurion.net/archives/2011/introduccio-al-bzr/#comments">No comments</a><br />
© Siegfried-Angel Gevatter Pujals, 2011. |
<a href="http://bloc.eurion.net/archives/2011/introduccio-al-bzr/">Permalink</a> |
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">License</a> |
Post tags: <a href="http://bloc.eurion.net/archives/tag/bzr/" rel="tag">bzr</a>, <a href="http://bloc.eurion.net/archives/tag/desenvolupament/" rel="tag">desenvolupament</a>, <a href="http://bloc.eurion.net/archives/tag/vcs/" rel="tag">vcs</a><br/>
</small></p><p class="wp-flattr-button"></p> <p><a href="http://bloc.eurion.net/?flattrss_redirect&amp;id=1389&amp;md5=b6e8f7e3339886eba515d337e14a0c4f" title="Flattr" target="_blank"><img src="http://bloc.eurion.net/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/introduccio-al-bzr/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Activity Log Manager for Zeitgeist released!</title>
		<link>http://bloc.eurion.net/archives/2011/activity-log-manager-released/</link>
		<comments>http://bloc.eurion.net/archives/2011/activity-log-manager-released/#comments</comments>
		<pubDate>Tue, 17 May 2011 14:40:46 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Planet GNOME]]></category>
		<category><![CDATA[Planet Ubuntu]]></category>
		<category><![CDATA[gnome]]></category>
		<category><![CDATA[Programari lliure]]></category>
		<category><![CDATA[zeitgeist]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1381</guid>
		<description><![CDATA[On behalf of the Activity Log Manager team and the Zeitgeist Project, I am&#160;happy to announce the first release of Activity Log Manager (0.8.0), a user interface for managing Zeitgeist blacklists,&#160;deleting recent events as well as temporarily pausing the logging. Grab it while it&#39;s hot. Note that you&#39;ll need Zeitgeist 0.8.0 (or later) for it [...]]]></description>
			<content:encoded><![CDATA[<p><meta content="text/html; charset=utf-8" http-equiv="content-type" /></p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0.8em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; width: auto; max-width: 45em; "><span class="Apple-style-span" style="color: rgb(51, 51, 51); font-family: 'UbuntuBeta Regular', Ubuntu, 'Bitstream Vera Sans', 'DejaVu Sans', Tahoma, sans-serif; line-height: 18px; ">On behalf of the Activity Log Manager team and the <a href="http://zeitgeist-project.com">Zeitgeist Project</a>, I am&nbsp;happy to announce the first release of <a href="https://launchpad.net/activity-log-manager">Activity Log Manager</a> (0.8.0), a user interface for managing Zeitgeist blacklists,&nbsp;deleting recent events as well as temporarily pausing the logging.</span></p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0.8em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; width: auto; max-width: 45em; text-align: center; "><span class="Apple-style-span" style="color: rgb(51, 51, 51); font-family: 'UbuntuBeta Regular', Ubuntu, 'Bitstream Vera Sans', 'DejaVu Sans', Tahoma, sans-serif; line-height: 18px; "><meta content="text/html; charset=utf-8" http-equiv="content-type" /><span class="Apple-style-span" style="color: rgb(34, 34, 34); font-family: Arial, Verdana, sans-serif; line-height: normal; "><a href="http://bloc.eurion.net/wp-content/uploads/2011/05/activity-log-manager.png"><img alt="" class="aligncenter size-medium wp-image-1382" height="214" src="http://bloc.eurion.net/wp-content/uploads/2011/05/activity-log-manager-300x214.png" style="cursor: default; " title="activity-log-manager" width="300" /></a></span></span></p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0.8em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; width: auto; max-width: 45em; "><span class="Apple-style-span" style="color: rgb(51, 51, 51); font-family: 'UbuntuBeta Regular', Ubuntu, 'Bitstream Vera Sans', 'DejaVu Sans', Tahoma, sans-serif; line-height: 18px; "><a href="https://launchpad.net/activity-log-manager/+download">Grab it</a> while it&#39;s hot. Note that you&#39;ll need Zeitgeist 0.8.0 (or later) for it to work. If you&#39;re an Ubuntu user you can get packages from <a href="https://launchpad.net/~zeitgeist/+archive/ppa">our PPA</a>; I&#39;ve also uploaded it to Debian.</span></p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0.8em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; width: auto; max-width: 45em; "><span class="Apple-style-span" style="color: rgb(51, 51, 51); font-family: 'UbuntuBeta Regular', Ubuntu, 'Bitstream Vera Sans', 'DejaVu Sans', Tahoma, sans-serif; line-height: 18px; ">I&#39;d also like to use this chance to thank <a href="http://collabora.com/">Collabora</a>&nbsp;for sponsoring my (and <a href="http://seilo.geekyogre.com/">Seif</a>&#39;s) work on Zeitgeist!</span></p>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2010/zeitgeist-0-5-1-released/' rel='bookmark' title='Zeitgeist 0.5.1 released!'>Zeitgeist 0.5.1 released!</a> <small>On behalf of the Zeitgeist Project team, I am pleased...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/zeitgeist-0-7-1-made-in-aarhus-released/' rel='bookmark' title='Zeitgeist 0.7.1 &#8220;Made in Aarhus&#8221; released!'>Zeitgeist 0.7.1 &#8220;Made in Aarhus&#8221; released!</a> <small>On behalf of the Zeitgeist team I am proud to...</small></li>
<li><a href='http://bloc.eurion.net/archives/2010/gnome-activity-journal-and-installing-it-on-ubuntu/' rel='bookmark' title='GNOME Activity Journal, and installing it on Ubuntu'>GNOME Activity Journal, and installing it on Ubuntu</a> <small>As already announced by Seif, the first development release of...</small></li>
</ol></p> <p><a href="http://bloc.eurion.net/?flattrss_redirect&amp;id=1381&amp;md5=352d2011dda24a36f79488075ba887f3" title="Flattr" target="_blank"><img src="http://bloc.eurion.net/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/activity-log-manager-released/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Zeitgeist 0.7.1 &#8220;Made in Aarhus&#8221; released!</title>
		<link>http://bloc.eurion.net/archives/2011/zeitgeist-0-7-1-made-in-aarhus-released/</link>
		<comments>http://bloc.eurion.net/archives/2011/zeitgeist-0-7-1-made-in-aarhus-released/#comments</comments>
		<pubDate>Sun, 20 Mar 2011 16:11:40 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Planet GNOME]]></category>
		<category><![CDATA[Planet Ubuntu]]></category>
		<category><![CDATA[Programari lliure]]></category>
		<category><![CDATA[zeitgeist]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1270</guid>
		<description><![CDATA[On behalf of the Zeitgeist team I am proud to announce the release of Zeitgeist 0.7.1 &#34;Made in Aarhus&#34;. This is a minor release before 0.8.0&#160;(which will be the first one introducing storage awareness). What is Zeitgeist? Zeitgeist is a service which logs the users&#39;s activities and events, anywhere from files opened to websites visited [...]]]></description>
			<content:encoded><![CDATA[<p>On behalf of the Zeitgeist team I am proud to announce the <a href="https://launchpad.net/zeitgeist/+announcement/7988">release</a> of Zeitgeist 0.7.1 &quot;Made in Aarhus&quot;. This is a minor release before <a href="https://launchpad.net/zeitgeist/+milestone/0.8.0">0.8.0</a>&nbsp;(which will be the first one introducing <a href="http://www.grillbar.org/wordpress/?p=536">storage awareness</a>).</p>
<p><strong>What is Zeitgeist?</strong></p>
<p>Zeitgeist is a service which logs the users&#39;s activities and events, anywhere from files opened to websites visited and conversations, and makes this information readily available for other applications to use. It is also able to establish relationships between items based on similarity and usage patterns.</p>
<p>The Zeitgeist engine is a user-level service and does not provide a GUI. It is intended to support dedicated journalling applications and deep integration with other desktop components.</p>
<p><strong>Where?</strong></p>
<p>Downloads: <a href="https://launchpad.net/zeitgeist/+download">launchpad.net/zeitgeist/+download</a> (<a href="http://launchpad.net/zeitgeist/0.7/0.7.1/+download/zeitgeist-0.7.1.tar.gz">zeitgeist-0.7.1.tar.gz</a>)</p>
<p>About Zeitgeist: <a href="http://zeitgeist-project.com">zeitgeist-project.com<br />
	</a>Wiki: <a href="http://wiki.zeitgeist-project.com">wiki.zeitgeist-project.com</a></p>
<p>See also <a href="https://launchpad.net/zeitgeist-datahub">Zeitgeist Datahub</a>, <a href="https://launchpad.net/gnome-activity-journal">GNOME Activity Journal</a> and the repository for additional <a href="https://launchpad.net/zeitgeist-dataproviders">Zeitgeist data-sources</a>. You may as well like <a href="https://launchpad.net/sezen">Sezen</a>.</p>
<p><strong>News since 0.7.0</strong></p>
<pre>Engine:

 - Expose property information in the D-Bus introspection output.
 - Mention column names explicitly when inserting events, for compatibility
   with the upcoming 0.8 release.

Python API:

 - Expose DataSourceRegistry&#39;s enabled status in a callback.
 - Automatically reconnect to Zeitgeist if the connection is lost when using
   methods asynchronously (so far this only happened for synchronous calls).
 - Reinstall all active monitors upon reconnection (LP: #673008, #727226).
 - Fix a (harmless) race condition requesting the bus name (LP: #732015).

Overall:

 - Added new event interpretation types: AcceptEvent, DenyEvent and ExpireEvent.
 - Include NCO in the generated ontologies.
 - Better ./configure check for python-rdflib.
 - Update the manpage to document exit codes.
</pre>
<p>Thanks to everyone who contributed to this release, and since I hadn&#39;t blogged about it before, also to everyone who made the <a href="http://live.gnome.org/Hackfests/Zeitgeist2011">Zeitgeist Hackfest in Aarhus</a> possible, including our sponsors:</p>
<p style="text-align: center; "><img alt="" class="aligncenter size-full wp-image-1276" height="57" src="http://bloc.eurion.net/wp-content/uploads/2011/03/collabora-logo-175.png" title="collabora-logo-175" width="175" />&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;<img alt="" class="aligncenter size-full wp-image-1280" height="84" src="http://bloc.eurion.net/wp-content/uploads/2011/03/incuba.gif" title="incuba" width="114" />&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;<img alt="" class="aligncenter size-medium wp-image-1279" height="41" src="http://bloc.eurion.net/wp-content/uploads/2011/03/aarhus-computer-science-300x41.png" title="aarhus-computer-science" width="300" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;<img alt="" height="100" src="http://bloc.eurion.net/wp-content/uploads/2009/11/gnome-sponsored-badge-150x150.png" width="100" /></p>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2010/zeitgeist-0-5-1-released/' rel='bookmark' title='Zeitgeist 0.5.1 released!'>Zeitgeist 0.5.1 released!</a> <small>On behalf of the Zeitgeist Project team, I am pleased...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/activity-log-manager-released/' rel='bookmark' title='Activity Log Manager for Zeitgeist released!'>Activity Log Manager for Zeitgeist released!</a> <small>On behalf of the Activity Log Manager team and the...</small></li>
<li><a href='http://bloc.eurion.net/archives/2010/zeitgeist-0-3-3-is-out/' rel='bookmark' title='Zeitgeist 0.3.3 is out!'>Zeitgeist 0.3.3 is out!</a> <small>From the release announcement: On behalf of the Zeitgeist Project...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/zeitgeist-0-7-1-made-in-aarhus-released/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>On Intel AppUp, the ExoPC Slate, MeeGo and Ubuntu 10.10</title>
		<link>http://bloc.eurion.net/archives/2011/on-intel-appup-the-exopc-slate-meego-and-ubuntu-10-10/</link>
		<comments>http://bloc.eurion.net/archives/2011/on-intel-appup-the-exopc-slate-meego-and-ubuntu-10-10/#comments</comments>
		<pubDate>Sat, 19 Feb 2011 21:51:29 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Planet Ubuntu]]></category>
		<category><![CDATA[intel]]></category>
		<category><![CDATA[meego]]></category>
		<category><![CDATA[mwc]]></category>
		<category><![CDATA[tablet]]></category>
		<category><![CDATA[touchscreen]]></category>
		<category><![CDATA[Ubuntu]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1233</guid>
		<description><![CDATA[Introduction (Intel Rocks!) Last Wednesday I attended the Intel AppUp Developer Day, a workshop where Intel employees presented the MeeGo stack and introduced Intel AppUp, a software center which will be shipping in netbooks/tablets/carputers/etc. There was also a live demo on how to design interfaces with QML and one of the Angry Birds creator said [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction (Intel Rocks!)</strong></p>
<p>Last Wednesday I attended the <a href="http://appdeveloper.intel.com/en-us/blog/2011/02/09/intel-appup-developer-program-mobile-world-congress">Intel AppUp Developer Day</a>, a workshop where Intel employees presented the MeeGo stack and introduced Intel AppUp, a software center which will be shipping in netbooks/tablets/carputers/etc. There was also a live demo on how to design interfaces with QML and one of the <a href="http://www.rovio.com/index.php?page=angry-birds">Angry Birds</a> creator said some words. Best of all, Intel was nice enough to give every participant a tablet!</p>
<p><strong>MeeGo (really alpha!)</strong></p>
<p>The ExoPC Slate came with&nbsp;Intel&#39;s new <a href="http://appdeveloper.intel.com/en-us/blog/2011/01/27/meego-tablets">tablet version of MeeGo</a>, which like its netbook counterpart seems to place great emphasis on social and multimedia uses, but it better suited for the touch screen. The system is still pre-alpha, though, and when I tried to use it lots of stuff failed to work. Asking about it at the MeeGo pavilion I was told to re-install the <a href="http://appdeveloper.intel.com/en-us/meego-sdk-suite">image</a>, which solved some of the problems. Still, I don&#39;t really see myself using it at this point, so I decided to also put Ubuntu on it.</p>
<p><strong>Installing Ubuntu</strong></p>
<p>The installation went smooth; I got a message about the bootloader not being able to be installed, but I just ignored it and had no problems. I had already left half of the 64GB SSD empty when installing MeeGo, since it uses brtfs which Ubuntu can&#39;t resize yet. Of course, I had to plug in mouse and keyboard (I used a USB hub, since the tablet only has two USB ports and one is required for the installation media). Boot is somewhat slower than what I&#39;d expect for an SSD, and sometimes shows some <a href="https://bugs.launchpad.net/ubuntu/+source/udev/+bug/647404">weird error messages</a>&nbsp;which seem to have no effect.</p>
<p>One outstanding problem is that GRUB doesn&#39;t support the touch screen (and for that matter neither does it recognize my wireless keyboard), so if I want to change between Ubuntu and MeeGo I have to plug in a normal USB keyboard.</p>
<p><strong>Getting the touch-screen to work (no multi-touch :()</strong></p>
<p>The touch-screen didn&#39;t work out of the box either but required some fiddling. Basically, I had to open /etc/default/boot and change &laquo;<em>GRUB_CMDLINE_LINUX_DEFAULT=&quot;quiet splash&quot;</em>&raquo; to &laquo;<em>GRUB_CMDLINE_LINUX_DEFAULT=&quot;quiet splash usbhid.quirks=0xeef:0x72a1:0&#215;40&quot;</em>&raquo; and run &laquo;<em>sudo update-grub</em>&raquo;, otherwise touching the screen would invariably send the pointer to the top-left. And basically, that&#39;s it, now it&#39;s working using the free drivers!</p>
<p>However, the free drivers only support a single finger. There&#39;s also the option of using the proprietary hid_egalax driver, which is supposed to correctly support tracking two fingers (and it does in MeeGo), but I didn&#39;t have so much luck in Ubuntu and functionally I don&#39;t really see a difference between them. To install it I downloaded the&nbsp;<a href="http://home.eeti.com.tw/web20/eGalaxTouchDriver/linuxDriver.htm">eGalaxTouch</a>&nbsp;tarball: <a href="http://home.eeti.com.tw/web20/drivers/touch_driver/Linux/20110117/eGalaxTouch-3.04.4912-32b-k26.tar.gz">eGalaxTouch-3.04.4912-32b-k26.tar.gz</a>. Then uncompressed the file, executed the setup script and restarted the computer. This time the result wasn&#39;t so nice, since in addition to still not doing any multi-touch, the pointer was showing up in the wrong place and somehow now the touch-screen device shows up four times. The pointer problem was easy to fix, though, by running XXXX and calibrating the four &quot;devices&quot;, so this basically left me just how I was with the free drivers.</p>
<p>Since with a single finger I have no way of triggering a right-click, I enabled the &quot;secondary click when pressing primary button&quot; accessibility option in the mouse preferences.</p>
<p><strong>Final touch (pun intended?)</strong></p>
<p>For typing I&#39;ve installed &quot;matchbox-keyboard&quot; and placed a launcher for it in the top panel. Suggestions on better alternatives are welcome (especially if they show up automatically when I focus a text box).</p>
<p>Now something I could do to at least get a little bit of coolness factor is enabling single-finger scroll support in Chromium, by installing the <a href="http://www.chromeextensions.org/appearance-functioning/chrometouch/">chromeTouch</a> extension (apparently there is also a similar extension for Firefox).</p>
<p>Finally, I disabled the key-binding for &quot;open music player&quot;, since by default the Slate&#39;s touch hot-key had been assigned to it and it kept opening Rhythmbox every time I accidentally went over the hot-key.</p>
<p><strong>References</strong></p>
<p>To wrap up this post, here&#39;s some random pages which helped me on my way here:</p>
<ul>
<li><a href="http://art.ubuntuforums.org/showthread.php?t=1541396">eGalax Touch Screen on Ubuntu 10.04</a></li>
<li><a href="http://samiux.blogspot.com/2010/11/howto-ubuntu-1010-on-gigabyte-touchnote.html">Ubuntu 10.10 on Gigabyte TouchNote T1028X</a></li>
<li><a href="http://wiki.meego.com/Installing_MeeGo_and_Handset_Images_on_ExoPC">Installing MeeGo and Handset Images on ExoPC</a></li>
<li><a href="http://ubuntuforums.org/showthread.php?t=1468376&amp;page=19">Ubuntu on EeePC T101MT</a></li>
<li><a href="http://www.exopc.com/forum/viewtopic.php?f=39&amp;t=2805#p44114">ExoPC does Ubuntu 10.10 Netbook</a></li>
<li><a href="https://help.ubuntu.com/community/EloTouchScreen">EloTouchScreen</a></li>
<li><a href="http://wiki.linuxmce.org/index.php/Egalax-Touchscreen">Egalax-TouchScreen</a></li>
<li><a href="https://wiki.ubuntu.com/X/Testing/Touchscreen">X/Testing/Touchscreen</a></li>
<li><a href="https://bugs.launchpad.net/ubuntu/+source/linux/+bug/549447">Bug #549447: eGalax touch-screen configured as tablet</a></li>
</ul>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2009/updated-voxforge-packages-in-ubuntu/' rel='bookmark' title='Updated Voxforge packages in Ubuntu'>Updated Voxforge packages in Ubuntu</a> <small>Just a quick note today to mention that I&#8217;ve updated...</small></li>
<li><a href='http://bloc.eurion.net/archives/2009/reducing-sshs-connection-time-on-ubuntu/' rel='bookmark' title='Reducing SSH&#8217;s connection time on Ubuntu'>Reducing SSH&#8217;s connection time on Ubuntu</a> <small>If you use SSH on your local network you may...</small></li>
<li><a href='http://bloc.eurion.net/archives/2010/gnome-activity-journal-and-installing-it-on-ubuntu/' rel='bookmark' title='GNOME Activity Journal, and installing it on Ubuntu'>GNOME Activity Journal, and installing it on Ubuntu</a> <small>As already announced by Seif, the first development release of...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/on-intel-appup-the-exopc-slate-meego-and-ubuntu-10-10/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Apunts d&#8217;Estructures de Dades i Algorismes: Programació dinàmica</title>
		<link>http://bloc.eurion.net/archives/2011/eda-programacio-dinamica/</link>
		<comments>http://bloc.eurion.net/archives/2011/eda-programacio-dinamica/#comments</comments>
		<pubDate>Thu, 13 Jan 2011 17:54:12 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[algorithmics]]></category>
		<category><![CDATA[eda]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1184</guid>
		<description><![CDATA[1. Nombres de Fibonacci L&#39;algorisme trivial per al c&#224;lcul dels nombres de Fibonacci repeteix molts c&#224;lculs. Podem evitar-ho desant tots els valors que calculem en una matriu i cercant-los all&#224; quan ens calguin abans de calcular-los un altre cop (memoization). Si nom&#233;s ens cal obtenir un sol nombre de Fibonacci, podem construir una versi&#243; iterativa [...]]]></description>
			<content:encoded><![CDATA[<h4>1. Nombres de Fibonacci</h4>
<p>L&#39;algorisme trivial per al c&agrave;lcul dels nombres de Fibonacci repeteix molts c&agrave;lculs. Podem evitar-ho desant tots els valors que calculem en una matriu i cercant-los all&agrave; quan ens calguin abans de calcular-los un altre cop (<em>memoization</em>). Si nom&eacute;s ens cal obtenir un sol nombre de Fibonacci, podem construir una versi&oacute; iterativa de l&#39;algorisme que eviti els c&agrave;lculs sense utilitzar espai de mem&ograve;ria addicional.</p>
<h4>2. Producte encadenat de matrius</h4>
<p>[FIXME: imatge multiplicaci&oacute; de matrius]. Hem vist que per multiplicar dues matrius podem utilitzar l&#39;algorisme escolar o l&#39;algorisme d&#39;Strassen. Amb el primer d&#39;ells, cal calcular \(\theta(pqr)\) productes escalars.</p>
<p>Si volem dur a terme una seq&uuml;&egrave;ncia de multiplicacions, el nombre de productes escalars a fer canvia significativament segons com posem els par&egrave;ntesis (el qual no t&eacute; cap efecte sobre el resultat). Per exemple, amb tres matrius \(A_1 = 10&#215;100\), \(A_2 = 100&#215;5\) i \(A_3 = 5&#215;50\), l&#39;operaci&oacute; \((A_1 \cdot A_2) A_3\) resulta en \(10 \cdot 100 \cdot 50 + 10 \cdot 5 \cdot 50 = 7500\) productes escalars. En canvi, l&#39;operaci&oacute; \(A_1 \cdot (A_2 \cdot A_3)\), amb les mateixes matrius, resultaria en \(100 \cdot 5 \cdot 50 + 10 \cdot 100 \cdot 50 = 75000\) productes escalars.</p>
<p>Heus aqu&iacute; el problema la multiplicaci&oacute; encadenada de matrius: on &laquo;posar&raquo; els par&egrave;ntesis per poder dur a terme les multiplicacions amb el m&iacute;nim nombre de productes escalars?</p>
<p>Per for&ccedil;a bruta, amb&nbsp;\(n\) matrius, les possibles formes de posar els par&egrave;ntesis s&oacute;n igual al nombre d&#39;arbres binaris amb&nbsp;\(n\) fulles, el qual correspon a \(C_n = \frac{1}{n + 1}{2n \choose n} \approx \frac{4^n}{3^{n/2}}\) (\(\small C\) &eacute;s el <a href="http://en.wikipedia.org/wiki/Catalan_number">nombre de Catalan</a>). Podem definir la seg&uuml;ent funci&oacute; per trobar el nombre m&iacute;nim de productes escalars per multiplicar les matrius&nbsp;\(A_i\), &#8230;, \(A_j\):</p>
\(m(i, j) = \begin{cases}0 &amp; i = j \\ min\left\{m(i, k) + m(k+1, j) + p_{i-1} \cdot p_k \cdot p_j\right\} &amp; i &lt; j\end{cases}\)
<p>Aquesta operaci&oacute; duplica c&agrave;lculs &rarr; memoritzaci&oacute;! En resulta el seg&uuml;ent codi C++ que triga temps \(\theta(n^3)\):</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">vector<span style="color: #000080;">&lt;</span>vector<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;&gt;</span> mem<span style="color: #008000;">&#40;</span>n<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span>, vector<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>n<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span>, <span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
vector<span style="color: #000080;">&lt;</span>vector<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;&gt;</span> tall<span style="color: #008000;">&#40;</span>n<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span>, vector<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span><span style="color: #008000;">&#40;</span>n<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span>, <span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">int</span> m<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i, <span style="color: #0000ff;">int</span> j<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>mem<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>j<span style="color: #008000;">&#93;</span> <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">return</span> mem<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>j<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>i <span style="color: #000080;">==</span> j<span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">return</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">int</span> s <span style="color: #000080;">=</span> MAX_INT<span style="color: #008080;">;</span> <span style="color: #666666;">// infinit</span>
    <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> k <span style="color: #000080;">=</span> i<span style="color: #008080;">;</span> k <span style="color: #000080;">&lt;=</span> j<span style="color: #008080;">;</span> <span style="color: #000040;">++</span>k<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">int</span> x <span style="color: #000080;">=</span> m<span style="color: #008000;">&#40;</span>i, k<span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> m<span style="color: #008000;">&#40;</span>k<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span>, j<span style="color: #008000;">&#41;</span> <span style="color: #000040;">+</span> p<span style="color: #008000;">&#91;</span>i<span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span> p<span style="color: #008000;">&#91;</span>k<span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span> p<span style="color: #008000;">&#91;</span>j<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>x <span style="color: #000080;">&lt;</span> s<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            s <span style="color: #000080;">=</span> x<span style="color: #008080;">;</span>
            tall<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>j<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> k<span style="color: #008080;">;</span> <span style="color: #666666;">// resposta al problema de com multiplicar-les</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0000ff;">return</span> m<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>j<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> s<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Tamb&eacute; podem construir-ne una versi&oacute; iterativa:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> i <span style="color: #000080;">&lt;=</span> n<span style="color: #008080;">;</span> <span style="color: #000040;">++</span>i<span style="color: #008000;">&#41;</span> mem<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span>
<span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> n<span style="color: #008080;">;</span> i <span style="color: #000080;">&gt;=</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> <span style="color: #000040;">--</span>i<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> j <span style="color: #000080;">=</span> i<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span><span style="color: #008080;">;</span> j <span style="color: #000080;">&lt;=</span> n<span style="color: #008080;">;</span> <span style="color: #000040;">++</span>j<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">int</span> s <span style="color: #000080;">=</span> MAX_INT<span style="color: #008080;">;</span> <span style="color: #666666;">// infinit</span>
        <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> k <span style="color: #000080;">=</span> i<span style="color: #008080;">;</span> k <span style="color: #000080;">&lt;=</span> j<span style="color: #008080;">;</span> <span style="color: #000040;">++</span>k<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            <span style="color: #0000ff;">int</span> x <span style="color: #000080;">=</span> mem<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>k<span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span> mem<span style="color: #008000;">&#91;</span>k<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>j<span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span> p<span style="color: #008000;">&#91;</span>i<span style="color: #000040;">-</span><span style="color: #0000dd;">1</span><span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span> p<span style="color: #008000;">&#91;</span>k<span style="color: #008000;">&#93;</span> <span style="color: #000040;">+</span> p<span style="color: #008000;">&#91;</span>j<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
            <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>x <span style="color: #000080;">&lt;=</span> s<span style="color: #008000;">&#41;</span> s <span style="color: #000080;">=</span> x<span style="color: #008080;">;</span>
        <span style="color: #008000;">&#125;</span>
        mem<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>j<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> s<span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<h4>3. Problema de la subseq&uuml;&egrave;ncia comuna m&eacute;s llarga</h4>
<p>Tenim dues cadenes X=&quot;abcbdab&quot; i Y=&quot;bdcaba&quot; i volem trobar la subseq&uuml;&egrave;ncia comuna (per exemple, &quot;bca&quot;) m&eacute;s llarga (en aquest cas, la m&eacute;s llarga &eacute;s &quot;bdab&quot;). Definim&nbsp;\(m=|X|\),&nbsp;\(n=|Y|\),&nbsp;\(X&#39;_i\)=\(X_1\)&#8230;\(X_i\).</p>
<ul>
<li>Si X i Y acaben igual: l&#39;&uacute;ltim car&agrave;cter d&#39;X (o Y) ha de ser l&#39;&uacute;ltim car&agrave;cter d&#39;LCS(X, Y).<br />
		LCS(X, Y) = \(LCS(X&#39;_{m-1}, Y&#39;_{n-1}) \cdot X_m\).</li>
<li>Si X i Y no acaben igual, pensem qu&egrave; passa amb LCS(X, Y).<br />
		\(LCS(X, Y) = \begin{cases}LCS(X_{n-1}, Y) \\ LCS(X, Y_{n-1})\end{cases}\) Quina de les dues? La m&eacute;s llarga.</li>
</ul>
<p>Definim la funci&oacute; \(l(i, j)\) = llargada de l&#39;LCS(\(X&#39;_i\), \(Y&#39;_i\)).</p>
\(l(i, j) = \begin{cases}0 &amp; i = 0 \text{ o } j=0 \\ l(i-1, j-1)+1 &amp; x_i = y_j \\ max\{l(i-1, j), l(i, j-1)\} &amp; sin\acute{o}\end{cases}\)
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/eda-dividir-i-vencer/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer'>Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer</a> <small>Introducci&oacute; L&#39;esquema de programaci&oacute; de dividir i v&egrave;ncer &eacute;s una...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-calcul-cost-algorismes/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs'>Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs</a> <small>Introducci&oacute; Els algorismes s&oacute;n per tot arreu i per aix&ograve;...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-grafs/' rel='bookmark' title='Apunts d’Estructures de Dades i Algorismes: Grafs'>Apunts d’Estructures de Dades i Algorismes: Grafs</a> <small>Definici&oacute; i propietats Graf: Graf dirigit (digraf): Un cam&iacute; de...</small></li>
</ol></p> <p><a href="http://bloc.eurion.net/?flattrss_redirect&amp;id=1184&amp;md5=b2b1af158d6aebb67f60f53850ac79c7" title="Flattr" target="_blank"><img src="http://bloc.eurion.net/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/eda-programacio-dinamica/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apunts d&#8217;Estructures de Dades i Algorismes: Les classes de problemes P i NP</title>
		<link>http://bloc.eurion.net/archives/2011/eda-p-np/</link>
		<comments>http://bloc.eurion.net/archives/2011/eda-p-np/#comments</comments>
		<pubDate>Wed, 12 Jan 2011 15:59:50 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[algorithmics]]></category>
		<category><![CDATA[eda]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1159</guid>
		<description><![CDATA[Classes de problemes &#8211; P i NP Entrades Problemes Classes de problemes (no excloents) P Coneixem algorismes amb temps pitjor polinomial (o millor) per a decidir el problema. NP Coneixem algorismes en temps polin&#242;mic indeterminista per a verificar si una soluci&#243; &#233;s correcta. Exemples de problemes que estan en NP: HAM &#8211; &#233;s dif&#237;cil trobar [...]]]></description>
			<content:encoded><![CDATA[<h4>Classes de problemes &ndash; P i NP</h4>
<table style="margin-top: 0.6em;">
<thead>
<tr>
<td>Entrades</td>
<td>Problemes</td>
<td colspan="2">Classes de problemes (no excloents)</td>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2" style="text-align: center;">\(x\)</td>
<td rowspan="2" style="text-align: center;">\(\pi\)</td>
<td><strong>P</strong></td>
<td>Coneixem algorismes amb temps pitjor polinomial (o millor) per a <strong>decidir</strong> el problema.</td>
</tr>
<tr>
<td><strong>NP</strong></td>
<td>Coneixem algorismes en <em>temps polin&ograve;mic indeterminista</em> per a <strong>verificar</strong> si una soluci&oacute; &eacute;s correcta.</td>
</tr>
</tbody>
</table>
<h5 style="margin-top: 1.2em;">Exemples de problemes que estan en NP:</h5>
<ul>
<li><strong>HAM</strong> &#8211; &eacute;s dif&iacute;cil trobar un cicle Hamiltoni&agrave; en un graf (<em>backtracking</em>), per&ograve; donada una sent&egrave;ncia de v&egrave;rtexs &eacute;s f&agrave;cil comprovar si &eacute;s una soluci&oacute;.</li>
<li><strong>Element m&iacute;nim</strong>.</li>
<li><strong>TSP</strong> (problema del viatjant de comer&ccedil;).</li>
<li><strong>Colorabilitat</strong>.</li>
<li><strong>Quadrat llat&iacute;</strong>.</li>
<li><strong>Sudoku</strong>.</li>
</ul>
<h5 style="margin-top: -10px;">Teorema</h5>
<p style="margin-top: 0.6em; margin-bottom: 1em;">\(P \subseteq NP\)</p>
<p style="margin-top: 0.6em; margin-bottom: 1em;">Queda una <a href="http://claymath.org/millennium/">pregunta clau</a>: \(P = NP\)?</p>
<h4>Reducci&oacute;</h4>
<p>Siguin \(L_1 \le E_1\) i \(L_2 \le E_2\) dos problemes decisionals. Diem que \(L_1\) es redueix a \(L_2\) en temps polin&ograve;mic si podem trobar un algorisme polin&ograve;mic \(A: L_1 \rightarrow L_2\), &eacute;s a dir, que converteixi tota soluci&oacute; a \(E_1\) en una soluci&oacute; d&#39;\(E_2\).</p>
<p>En altres paraules, una reducci&oacute; en temps polin&ograve;mic d&#39;\(L_1\) a&nbsp;\(L_2\) &eacute;s un algorise&nbsp;\(R: E_1 \rightarrow E2 / \forall x \in E_1: x \in L1 \Leftrightarrow R(x) \in L_2\).</p>
<p>Podem reduir, per exemple, el problema del graf hamiltoni&agrave; (HAM) al problema del viatjant de comer&ccedil; (TSP).</p>
<p><strong>Teorema:</strong> Si \(L_1 \le_p L_2\) i \(L_2 \in P\), llavors \(L_1 \in P\).</p>
<p>Un problema decisional \(L\) &eacute;s <strong>NP-hard</strong> si tot problema en NP es pot reduir a ell en temps polin&ograve;mic. \(L \in \text{NP-hard} \Leftrightarrow \forall L&#39; \in NP, L&#39; \le_p L\).</p>
<p>Un problema &eacute;s <strong>NP-complet</strong> si &eacute;s NP-hard i es troba en NP.</p>
<p><strong>Teorema:<br />
	</strong>\(L \in NP-hard, L \in P \Leftrightarrow P = NP\).</p>
<p><strong>Teorema:<br />
	</strong>\(\left\{\begin{array}{l}L_1 \in \text{NP-C} \\ L_2 \in NP \\ L_1 \hookrightarrow L_2\end{array}\right\} L_2 \in NP-C\)</p>
<p><strong>Teorema de Cook&nbsp;</strong>(~1970)<br />
	\(\small\text{CIRCUIT-SAT} \normalsize\in \small\text{NP-C}\) (va ser el primer problema NP-complet).</p>
<p>El problema decisional <strong>CIRCUIT-SAT</strong>&nbsp;pren com a entrada un circuit amb&nbsp;\(n\) entrades booleanes, una sortida i portes AND, OR i NOT i el que pregunta &eacute;s, &laquo;hi ha alguna entrada del circuit que faci que la sortida sigui 1?&raquo;.</p>
<p>Nota: Una possible soluci&oacute; donada per justificar que un problema decisional t&eacute; soluci&oacute; s&#39;anomena <strong>testimoni</strong>.</p>
<h4>Solucions pr&agrave;ctiques per a problemes NP</h4>
<ul>
<li>Heur&iacute;stiques.</li>
<li>Aproximacions.</li>
<li>Paral&middot;lelisme, ordinadors qu&agrave;ntics&#8230;</li>
</ul>
<h4>El problema de l&#39;aturada</h4>
<p>A part de les classes de problemes P, NP i NP-C n&#39;hi ha moltes d&#39;altres, i una d&#39;elles que cal mencionar &eacute;s la dels problemes <strong>irresolubles</strong>: aquells que l&#39;ordinador (o millor dit, una m&agrave;quina de Turing) no pot solucionar.</p>
<p>Un exemple de problema irresoluble &eacute;s el de l&#39;<strong>aturada</strong>: donada la descripci&oacute; d&#39;un programa i el seu estat inicial, determinar si el programa, si l&#39;executem, arribar&agrave; a completar-se o b&eacute; funcionar&agrave; fins la fi de l&#39;eternitat. Podem veure-ho amb el seg&uuml;ent programa d&#39;exemple:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">typedef</span> String Programa<span style="color: #008080;">;</span>
<span style="color: #0000ff;">typedef</span> String Entrada<span style="color: #008080;">;</span>
&nbsp;
<span style="color: #666666;">// Funci&amp;oacute; que retorna cert si el programa p, donada l&amp;#39;entrada</span>
<span style="color: #666666;">// x, arriba a aturar-se</span>
<span style="color: #0000ff;">bool</span> acaba<span style="color: #008000;">&#40;</span>Programa p, Entrada x<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
&nbsp;
<span style="color: #0000ff;">void</span> vinga<span style="color: #008000;">&#40;</span>Programa p<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #666666;">// Entra en un bucle infinit si el programa p, donant-li com a entrada</span>
    <span style="color: #666666;">// el mateix codi del programa, arriba a aturar-se</span>
    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>acaba<span style="color: #008000;">&#40;</span>p, p<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">true</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Si analitzem aquest programa i executem <em>vinga(vinga)</em> veiem que pot haver-hi dos casos:</p>
<ol>
<li>Que acabi &#8211; si acaba, <em>vinga</em> entra en el bucle i no acaba &rarr; contradicci&oacute;.</li>
<li>Que no acabi &#8211; si no acaba, <em>vinga</em> acaba &rarr; contradicci&oacute;.</li>
</ol>
<p style="margin-top: -10px;">Aix&iacute; doncs, no es pot solucionar el problema de l&#39;aturada.</p>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/eda-cerca-exhaustiva/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Cerca exhaustiva'>Apunts d&#8217;Estructures de Dades i Algorismes: Cerca exhaustiva</a> <small>Cerca exhaustiva La cerca exhaustiva &eacute;s un m&egrave;tode de disseny...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-dividir-i-vencer/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer'>Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer</a> <small>Introducci&oacute; L&#39;esquema de programaci&oacute; de dividir i v&egrave;ncer &eacute;s una...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-grafs/' rel='bookmark' title='Apunts d’Estructures de Dades i Algorismes: Grafs'>Apunts d’Estructures de Dades i Algorismes: Grafs</a> <small>Definici&oacute; i propietats Graf: Graf dirigit (digraf): Un cam&iacute; de...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/eda-p-np/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apunts d&#8217;Estructures de Dades i Algorismes: Cerca exhaustiva</title>
		<link>http://bloc.eurion.net/archives/2011/eda-cerca-exhaustiva/</link>
		<comments>http://bloc.eurion.net/archives/2011/eda-cerca-exhaustiva/#comments</comments>
		<pubDate>Wed, 12 Jan 2011 15:26:29 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[algorithmics]]></category>
		<category><![CDATA[eda]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1143</guid>
		<description><![CDATA[Cerca exhaustiva La cerca exhaustiva &#233;s un m&#232;tode de disseny d&#39;algorismes que consisteix en mirar-se sistem&#224;tica i intel&#183;ligentment totes les possibles solucions a un problema donat. Generalment els problemes que es resolen mitjan&#231;ant aquesta t&#232;cnica s&#243;n problemes d&#39;optimitzaci&#243; o combinatoris. La t&#232;cnica consisteix en generar impl&#237;citament un arbre representant totes les possibles solucions i explorar-lo [...]]]></description>
			<content:encoded><![CDATA[<h4>Cerca exhaustiva</h4>
<p>La <strong>cerca exhaustiva</strong> &eacute;s un m&egrave;tode de disseny d&#39;algorismes que consisteix en mirar-se sistem&agrave;tica i <em>intel&middot;ligentment</em> totes les possibles <em>solucions</em> a un problema donat.</p>
<p>Generalment els problemes que es resolen mitjan&ccedil;ant aquesta t&egrave;cnica s&oacute;n problemes d&#39;optimitzaci&oacute; o combinatoris.</p>
<p>La t&egrave;cnica consisteix en generar impl&iacute;citament un arbre representant totes les possibles solucions i explorar-lo en profunditat, deixant de rec&oacute;rrer aquelles branques que corresponguin a &laquo;candidats a soluci&oacute;&raquo; que no compleixen les restriccions del problema donat. Nosaltres la veurem per <strong><em>backtracking</em></strong>.</p>
<h5>Exemple. El problema de les &laquo;n&raquo; reines</h5>
<p>Donat un tauler d&#39;\(n\)x\(n\) caselles i&nbsp;\(n\) reines, cal situar-les de manera que no s&#39;amenacin entre elles (segons les regles dels escacs). V&eacute;s aqu&iacute; algunes opcions:</p>
<ol>
<li>Podem mirar totes les possibles configuracions i veure quines compleixen les restriccions del problema. Aix&ograve; s&oacute;n&nbsp;\(n^2 \choose n\) combinacions; amb&nbsp;\(n=8\) aix&ograve; s&oacute;n&nbsp;\({64 \choose 8} = 4426165368\) possibilitats.</li>
<li>Podem limitar-nos a posar una &uacute;nica reina en cada l&iacute;nia. Aix&ograve; s&oacute;n&nbsp;\(n^n\) possibilitats; amb&nbsp;\(n=8\),&nbsp;\(8^8 = 16777216\).</li>
<li>Podem posar una &uacute;nica reina en cada fila i columna. Aix&ograve; s&oacute;n&nbsp;\(n!\) possibilitats; amb&nbsp;\(n=8\),&nbsp;\(8! = 40320\).</li>
<li>Podem posar una &uacute;nica reina en cada fila, columna i diagonal.</li>
</ol>
<p>El problema amb aquestes propostes &eacute;s que fins que no hem acabat de construir una configuraci&oacute; no es mira si les condicions es compleixen o no. Ja en podr&iacute;em desestimar moltes mentre s&#39;estan construint: utilitzem la t&egrave;cnica del <em>backtracking</em>.</p>
<p>Una part important d&#39;aquesta t&egrave;cnica consisteix en determinar una manera per a representar les possibles configuracions (solucions) del problema. En el cas de les reines, ho farem amb una taula d&#39;\(n\) posicions, tal que&nbsp;\(v[i]\) &eacute;s la columna on va la reina i que al tauler anir&agrave; en&nbsp;\((i, v[i])\).</p>
<p>Definim un vector&nbsp;\(k\)-completable de la seg&uuml;ent manera: sigui&nbsp;\((k-1)\)-completable, i&nbsp;\(\forall i\ tal\ que\ 1 \le i \le k-1, v[i] \ne v[k], i + v[i] \ne k + v[k], n &#8211; v[i] + i \ne n &#8211; v[k] + k\). Les solucions al problema de les&nbsp;\(n\) reines s&oacute;n els vector&nbsp;\(n\)-completables.</p>
<p>Observacions:</p>
<ol>
<li>\(i \ne j, \forall 1 \le i, j \le k, v[i] \ne v[j], v[i] + i \ne v[j] + j,\) \(n &#8211; 1 &#8211; v[i] + i \ne n &#8211; 1 &#8211; v[j] + j\) (les dues darrers condicions cobreixen les diagonals).</li>
<li>El vector ha de ser&nbsp;\((k &#8211; 1)\)-completable i, a m&eacute;s,&nbsp;\(\forall 1 \le i \le k &#8211; 1, v[i] \ne v[k], v[i] + i \ne v[k] + k, n &#8211; 1 &#8211; v[i] + i \ne n -1 &#8211; v[k] + k\).</li>
<li>Tots els vectors s&oacute;n&nbsp;\(1\)-completables.</li>
<li>Les solucions al problema s&oacute;n els vectors n-completables.</li>
</ol>
<h5>Exemple. El problema de la motxilla</h5>
<p>&laquo;Una motxilla t&eacute; lloc per a C unitats de pes. Tria d&#39;entre&nbsp;\(n\) objectes amb pesos&nbsp;\(p[i], &#8230;, p[n]\) i valor&nbsp;\(v[i], &#8230;, v[n]\) la combinaci&oacute; d&#39;objectes amb pes total inferior a C amb el valor m&agrave;xim&raquo;.</p>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/eda-p-np/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Les classes de problemes P i NP'>Apunts d&#8217;Estructures de Dades i Algorismes: Les classes de problemes P i NP</a> <small>Classes de problemes &ndash; P i NP Entrades Problemes Classes...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-dividir-i-vencer/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer'>Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer</a> <small>Introducci&oacute; L&#39;esquema de programaci&oacute; de dividir i v&egrave;ncer &eacute;s una...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-programacio-dinamica/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Programació dinàmica'>Apunts d&#8217;Estructures de Dades i Algorismes: Programació dinàmica</a> <small>1. Nombres de Fibonacci L&#39;algorisme trivial per al c&agrave;lcul dels...</small></li>
</ol></p> <p><a href="http://bloc.eurion.net/?flattrss_redirect&amp;id=1143&amp;md5=5cea2bb0cb5b29e1ab708dfdc00bffd9" title="Flattr" target="_blank"><img src="http://bloc.eurion.net/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/eda-cerca-exhaustiva/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apunts d’Estructures de Dades i Algorismes: Grafs</title>
		<link>http://bloc.eurion.net/archives/2011/eda-grafs/</link>
		<comments>http://bloc.eurion.net/archives/2011/eda-grafs/#comments</comments>
		<pubDate>Wed, 12 Jan 2011 12:39:57 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[algorithmics]]></category>
		<category><![CDATA[eda]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1103</guid>
		<description><![CDATA[Definici&#243; i propietats Graf: Graf dirigit (digraf): Un cam&#237; de longitud &#233;s una seq&#252;&#232;ncia de v&#232;rtexs connectats (per arrestes/arcs) entre ells. Si tots els v&#232;rtexs s&#243;n diferents, el cam&#237; &#233;s simple. Un cicle &#233;s un cam&#237; simple amb la peculiaritat que comen&#231;a i acaba al mateix v&#232;rtex. El di&#224;metre d&#39;un graf &#233;s el m&#224;xim de [...]]]></description>
			<content:encoded><![CDATA[<h4>Definici&oacute; i propietats</h4>
<p><strong>Graf</strong>:<br />
	\(\begin{array}{lll}G: &amp; \small V\grave{e}rtexs/Nodes &amp; V = \{1, 2, 3, 4\} \\ &amp; \small Arestes &amp; E = \left\{\{1, 2\}, \{1, 3\}, \{2, 3\}, \{3, 4\}\right\}\end{array}\)</p>
<p><strong>Graf dirigit</strong> (<em>digraf</em>):<br />
	\(\begin{array}{lll}G&#39;: &amp; \small V\grave{e}rtexs/Nodes &amp; V = \{1, 2, 3, 4\} \\ &amp; \small Arcs &amp; E \subset VxV\ \small (un\ arc\ \acute{e}s\ un\ parell\ ordenat\ de\ v\grave{e}rtexs)\\ &amp; &amp; E = \left\{(1, 2), (1, 3), (2, 3), (3, 4)\right\}\end{array}\)</p>
<p>Un <strong>cam&iacute;</strong> de longitud \(l\) &eacute;s una seq&uuml;&egrave;ncia de v&egrave;rtexs connectats (per arrestes/arcs) entre ells. Si tots els v&egrave;rtexs s&oacute;n diferents, el cam&iacute; &eacute;s <strong>simple</strong>. Un <strong>cicle</strong> &eacute;s un cam&iacute; simple amb la peculiaritat que comen&ccedil;a i acaba al mateix v&egrave;rtex.</p>
<p>El <strong>di&agrave;metre</strong> d&#39;un graf &eacute;s el m&agrave;xim de tots els camins m&iacute;nims.</p>
<p>Diem que un graf&nbsp;\(G = (V, E)\) &eacute;s <strong>connex</strong> si per tot parell de v&egrave;rtexs&nbsp;\(u, v \in V\) existeix un cam&iacute; que comen&ccedil;a en&nbsp;\(u\) i acaba en&nbsp;\(v\).</p>
<p>Un graf no dirigit, connex i ac&iacute;clic (sense cicles) &eacute;s un <strong>arbre</strong> (<em>arbre lliure</em>); &eacute;s un graf no dirigit on hi ha exactament un cam&iacute; entre cada parell de v&egrave;rtexs. Els arbres tenen les seg&uuml;ents propietats:</p>
<ul>
<li>un arbre amb&nbsp;\(n\) v&egrave;rtex t&eacute;&nbsp;\(n &#8211; 1\) arestes;</li>
<li>si s&#39;afegeix una aresta a un arbre llavors tindr&agrave; un (&uacute;nic) cicle;</li>
<li>si s&#39;elimina una aresta d&#39;un arbre llavors deixa de ser connex.</li>
</ul>
<p><span id="more-1103"></span></p>
<p>Un graf dirigit &eacute;s <strong>fortament connex</strong>&nbsp;si tots els parells de v&egrave;rtexs (considerant l&#39;ordre) tenen un cam&iacute; que els uneix, i <strong>d&egrave;bilment connex</strong> si &eacute;s connex al convertir-lo en un graf no dirigit.</p>
<p>Un v&egrave;rtex&nbsp;\(v\) &eacute;s <strong>adjacent</strong> al v&egrave;rtex&nbsp;\(u\) si&nbsp;\(\{u, v\} \in E\) (\((u, v) \in E\) si &eacute;s un graf dirigit).</p>
<p>El <strong>grau</strong> d&#39;un v&egrave;rtex &eacute;s el nombre de v&egrave;rtexs adjacents a ell i el grau d&#39;un graf &eacute;s el grau m&agrave;xim dels v&egrave;rtexs.</p>
<p>En grafs no dirigits,&nbsp;\(G = (V, E)\), es compleix el seg&uuml;ent teorema:&nbsp;\(\sum_{u \in v}grau(u) = 2|E|\).</p>
<p>Un graf &eacute;s <strong>complet</strong> si cont&eacute; el m&agrave;xim nombre d&#39;arestes/arcs possible. En el cas d&#39;un graf aquest &eacute;s&nbsp;\(\frac{n(n-1)}{2}\) i en el cas d&#39;un graf dirigit&nbsp;\(n(n-1)\).</p>
<p>Un graf connex i no dirigit &eacute;s <strong>Euleri&agrave;</strong> si i nom&eacute;s si existeix un cam&iacute; que inclou cada aresta del graf exactament un cop.</p>
<p>Un graf &eacute;s <strong>Hamiltoni&agrave;</strong> si i nom&eacute;s si cont&eacute; un cicle Hamiltoni&agrave; (un cicle simple de longitud&nbsp;\(|V|\)).</p>
<p>Un graf &eacute;s <strong>planar</strong> si &eacute;s possible representar-lo en paper sense que es creui cap l&iacute;nia. El teorema de Kuratowski afirma que nom&eacute;s el grafs que no contenen&nbsp;\(k_{3,3}\) (el graf complet bipartit de 6 v&egrave;rtexs) ni&nbsp;\(K_5\) (el graf complet de 5 v&egrave;rtexs) s&oacute;n planars. Enlla&ccedil;: <a href="http://ca.wikipedia.org/wiki/Graf_planar">article a la Viquip&egrave;dia</a>.</p>
<p>Els grafs tamb&eacute; poden tenir les seg&uuml;ents caracter&iacute;stiques, que no utilitzarem en aquest curs:</p>
<ul>
<li>Bucle (<em>loop</em>): aresta/arc que comen&ccedil;a i acaba en el mateix v&egrave;rtex.</li>
<li>Multigrafs: graf amb m&eacute;s d&#39;una aresta/arc connectant el mateix parell de v&egrave;rtexs.</li>
</ul>
<h4>Implementaci&oacute;</h4>
<p>El tipus abstracte de dades (TAD) <em>graf</em> compta amb m&egrave;todes com <em>crea</em>, <em>inserta_aresta</em>, <em>compta_vertex</em>, etc. Les dades es poden representar de diverses maneres.</p>
<h5>Matriu d&#39;ajdac&egrave;ncia</h5>
<p>Consisteix en representar el graf en una matriu de booleans \(n x n\). Per a grafs no dirigits i sense bucles, &eacute;s una matriu triangular, sim&egrave;trica en els dos costats.</p>
<p>&#8230; [FIXME: aqu&iacute; van dues imatges d&#39;exemple i les matrius corresponents] &#8230;</p>
<ul>
<li>Espai: \(\theta(n^2)\)</li>
<li>Temps de creaci&oacute;: \(\Omega(n^2)\) (\(\theta(n^2)\) m&eacute;s el temps de lectura del graf)</li>
</ul>
<h5>Llista d&#39;adjac&egrave;ncia</h5>
<table style="width: 100%; border: 0;">
<tbody>
<tr style="border: 0;">
<td style="border: 0;">
<table>
<tbody>
<tr>
<td>1</td>
<td>2, 3</td>
</tr>
<tr>
<td>2</td>
<td>1, 4</td>
</tr>
<tr>
<td>3</td>
<td>1, 4, 5</td>
</tr>
<tr>
<td>4</td>
<td>2, 3, 6</td>
</tr>
<tr>
<td>5</td>
<td>3, 6</td>
</tr>
<tr>
<td>6</td>
<td>4, 5</td>
</tr>
</tbody>
</table>
</td>
<td style="border: 0;">

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">typedef</span> vector<span style="color: #000080;">&lt;</span>list<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;&gt;</span> graf<span style="color: #008080;">;</span>
<span style="color: #666666;">// o millor:</span>
<span style="color: #0000ff;">typedef</span> vector<span style="color: #000080;">&lt;</span>vector<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;&gt;</span> graf<span style="color: #008080;">;</span></pre></div></div>

</td>
</tr>
</tbody>
</table>
<ul>
<li>Espai: \(\theta(n + m)\) on \(n\) &eacute;s el nombre de v&egrave;rtex i \(m\) el nombre d&#39;arestes.</li>
</ul>
<h5>Quina de les representacions &eacute;s m&eacute;s convenient?</h5>
<p>La matriu &eacute;s m&eacute;s eficient en temps (acc&egrave;s directe a qualsevol posici&oacute; en \(\theta(1)\)) per&ograve; en espai pot ser molt ineficient (quan cont&eacute; molts zeros, en el cas de grafs esparsos). Utilitzem la matriu per a grafs densos (\(|E| = \theta(n^2)\)).</p>
<p><strong>Exemple</strong></p>
<p>Tenim un graf amb \(n = 4182\) v&egrave;rtex i \(m = 12384\) arestes.</p>
<p>L&#39;espai en mem&ograve;ria que aquest ocupar&agrave; en cas d&#39;utilitzar una matriu d&#39;adjac&egrave;ncia, suposant que un boole&agrave; ocupa un byte, &eacute;s \(\frac{4182^2}{2} \simeq 8.34MB\) (suposant que un boole&agrave; ocupa un bit, serien \(\frac{4182^2}{2 \cdot 8} = 1.04MB\)).</p>
<p>Si en lloc d&#39;una matriu utilitzem una llista d&#39;adjac&egrave;ncia, on cada enter (o punter) ocupa 4 bytes, l&#39;espai que ocupar&agrave; &eacute;s \(4182 \cdot 4 + 12384 \cdot 4 \cdot 2 = 0.11MB\) (multipliquem per 2 al suposar que es tracta d&#39;un graf no dirigit).</p>
<h4>Recorreguts</h4>
<p>Un <strong>recorregut</strong> &eacute;s una manera sistem&agrave;tica de visitar tots els v&egrave;rtex d&#39;un graf.</p>
<h5>Recorregut en profunditat</h5>
<p>El <strong>recorregut en profunditat</strong> (DFS, <em>depth first search</em>), similar al recorregut en pre-ordre dels arbres, consisteix en visitar un v&egrave;rtex i continuar el recorregut amb un v&egrave;rtex adjacent o l&#39;&uacute;ltim v&egrave;rtex visitat que no hagi estat visitat fins ara.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">list<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span> dfs<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> graf<span style="color: #000040;">&amp;</span> G<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    list<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span> L<span style="color: #008080;">;</span>
    vector<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">bool</span><span style="color: #000080;">&gt;</span> visitat<span style="color: #008000;">&#40;</span>G.<span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, <span style="color: #0000ff;">false</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    stack<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span> S<span style="color: #008080;">;</span>
    <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> i <span style="color: #000080;">&lt;</span> G.<span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #000040;">++</span>i<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>not visitat<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            S.<span style="color: #007788;">push</span><span style="color: #008000;">&#40;</span>i<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
            <span style="color: #0000ff;">while</span> <span style="color: #008000;">&#40;</span>not S.<span style="color: #007788;">empty</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                <span style="color: #0000ff;">int</span> v <span style="color: #000080;">=</span> S.<span style="color: #007788;">top</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> S.<span style="color: #007788;">pop</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
                L.<span style="color: #007788;">push_back</span><span style="color: #008000;">&#40;</span>v<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> visitat<span style="color: #008000;">&#91;</span>v<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff;">true</span><span style="color: #008080;">;</span>
                <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> w <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> w <span style="color: #000080;">&lt;</span> G<span style="color: #008000;">&#91;</span>v<span style="color: #008000;">&#93;</span>.<span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #000040;">++</span>w<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>not visitat<span style="color: #008000;">&#91;</span>G<span style="color: #008000;">&#91;</span>v<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>w<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> S.<span style="color: #007788;">push</span><span style="color: #008000;">&#40;</span>G<span style="color: #008000;">&#91;</span>v<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>w<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
                <span style="color: #008000;">&#125;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0000ff;">return</span> L<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<h5>Recorregut en amplada</h5>
<p>El <strong>recorregut en amplada</strong> (BFS, <em>breadth first search</em>) &eacute;s similar al recorregut per nivells en un arbre. La implementaci&oacute; &eacute;s similar a la del recorregut en profunditat, per&ograve; utilitzant una cua en lloc d&#39;una pila.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;">list<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span> bfs<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">const</span> graf<span style="color: #000040;">&amp;</span> G<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    list<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span> L<span style="color: #008080;">;</span>
    vector<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">bool</span><span style="color: #000080;">&gt;</span> encuat<span style="color: #008000;">&#40;</span>G.<span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, <span style="color: #0000ff;">false</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    queue<span style="color: #000080;">&lt;</span><span style="color: #0000ff;">int</span><span style="color: #000080;">&gt;</span> Q<span style="color: #008080;">;</span>
    <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> i <span style="color: #000080;">&lt;</span> G.<span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #000040;">++</span>i<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>not encuat<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            Q.<span style="color: #007788;">push</span><span style="color: #008000;">&#40;</span>i<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> encuat<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff;">true</span><span style="color: #008080;">;</span>
            <span style="color: #0000ff;">while</span> <span style="color: #008000;">&#40;</span>not Q.<span style="color: #007788;">empty</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                <span style="color: #0000ff;">int</span> v <span style="color: #000080;">=</span> Q.<span style="color: #007788;">front</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> Q.<span style="color: #007788;">pop</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
                L.<span style="color: #007788;">push_back</span><span style="color: #008000;">&#40;</span>v<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
                <span style="color: #0000ff;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> w <span style="color: #000080;">=</span> <span style="color: #0000dd;">0</span><span style="color: #008080;">;</span> w <span style="color: #000080;">&lt;</span> G<span style="color: #008000;">&#91;</span>v<span style="color: #008000;">&#93;</span>.<span style="color: #007788;">size</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> <span style="color: #000040;">++</span>w<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>not encuat<span style="color: #008000;">&#91;</span>G<span style="color: #008000;">&#91;</span>v<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>w<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                        Q.<span style="color: #007788;">push</span><span style="color: #008000;">&#40;</span>G<span style="color: #008000;">&#91;</span>v<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>w<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span> encuat<span style="color: #008000;">&#91;</span>G<span style="color: #008000;">&#91;</span>v<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#91;</span>w<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff;">true</span><span style="color: #008080;">;</span>
                    <span style="color: #008000;">&#125;</span>
                <span style="color: #008000;">&#125;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0000ff;">return</span> L<span style="color: #008080;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<h5>Ordenaci&oacute; topol&ograve;gica</h5>
<p>Donat un graf dirigit i ac&iacute;clic (DAG, <em>directed acyclic graph</em>), \(G = \{V, E\}\), una <strong>ordenaci&oacute; topol&ograve;gica</strong> de&nbsp;\(G\) &eacute;s una ordenaci&oacute; dels seus v&egrave;rtexs tal que per tot parell de v&egrave;rtexs&nbsp;\(u, v \in V\), si existeix un cam&iacute; d&#39;\(u\) a&nbsp;\(v\) al graf&nbsp;\(G\), aleshores&nbsp;\(v\) no pot apar&egrave;ixer abans que&nbsp;\(u\) a l&#39;ordenaci&oacute;.</p>
<p>Algorisme: Calculem el grau d&#39;entrada (el n&uacute;mero d&#39;arcs entrants) de tots els nodes. Afegim aquells on el grau &eacute;s zero en una pila i restem 1 al grau de tots els seus nodes adjacents; aquells adjacents que passin a grau 0 tamb&eacute; els afegim a la pila.</p>
<p>Com podem veure, l&#39;ordenaci&oacute; topol&ograve;gica &eacute;s una aplicaci&oacute; del recorregut en profunditat. Tamb&eacute; &eacute;s evident que no &eacute;s &uacute;nica, ja que pot tenir molts resultats possibles:</p>
<p><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/Possibilitats-de-lordenacio-topològica.png"><img alt="" class="aligncenter size-medium wp-image-1138" height="224" src="http://bloc.eurion.net/wp-content/uploads/2011/01/Possibilitats-de-lordenacio-topològica-300x224.png" title="Possibilitats de l'ordenacio topològica" width="300" /></a></p>
<h5>Algorisme de Dijkstra</h5>
<p>Un graf \(G = \{V, E\}\) &eacute;s un&nbsp;<strong>graf amb pesos</strong> (<em>weighted graph</em>) si cada aresta \(\{u, v\}\) (o arc&nbsp;\((u, v)\)) del graf t&eacute; associat un valor&nbsp;\(w \in \mathbb{R}\). Si \(w \in \mathbb{R}^{+}\),&nbsp;\(G\) &eacute;s un graf amb pesos positius; si&nbsp;\(w \in \mathbb{R}^{+} \cup \{0\}\), &eacute;s un graf amb pesos no negatius.</p>
<p>Donat un graf&nbsp;\(G\) amb pesos, el pes (tamb&eacute; anomenat valor, cost o dist&agrave;ncia, si els pesos s&oacute;n positius) &eacute;s la suma dels pesos de les arestes (o arcs) del cam&iacute;.</p>
<p>Donats dos v&egrave;rtexs&nbsp;\(u, v \in V\) qualssevol, diem que un cam&iacute; d&#39;\(u\) a&nbsp;\(v\) &eacute;s m&iacute;nim (o de pes m&iacute;nim) si el seu pes &eacute;s m&eacute;s petit o igual que el pes de qualsevol altre cam&iacute; d&#39;\(u\) a&nbsp;\(v\). (Si no hi ha cap cami d&#39;\(u\) a&nbsp;\(v\) diem, per definici&oacute;, que el pes &eacute;s&nbsp;\(\infty\)).</p>
<p>L&#39;<strong>algorisme de Dijkstra</strong> (pronunciaci&oacute;: &#39;d3Ikstra) calcula els camins m&iacute;nims d&#39;un v&egrave;rtexs&nbsp;\(v\)&nbsp;cap a tots els altres v&egrave;rtexs del graf. Es tracta d&#39;un algorisme <strong>vora&ccedil;</strong> (<em>greedy</em>).</p>
<p>&#8230; [FIXME: aqu&iacute; va un exemple] &#8230;</p>
<p>Observacions:</p>
<ul>
<li>L&#39;algorisme de Dijkstra no funciona si hi ha pesos negatius.</li>
<li>El seu cost &eacute;s&nbsp;\(O(n^2)\).</li>
</ul>
<h4>An&agrave;lisi de costs</h4>
<h5 style="margin-top: 0.6em;">Cost del recorregut en amplada</h5>
<ol>
<li>Cada v&egrave;rtex del graf entra i surt de la cua exactament una vegada. Aix&ograve; correspon a un temps \(\theta(|V|)\).</li>
<li>La llista d&#39;adjac&egrave;ncies de cada v&egrave;rtex es recorre una &uacute;nica vegada, en el moment de treure el v&egrave;rtex de la cua. Per tant, per cada v&egrave;rtex&nbsp;\(u\) aix&ograve; correspon a un temps&nbsp;\(\theta(Adj(u))\), i en total, per a tots els v&egrave;rtexs, aix&ograve; correspon a un temps&nbsp;\(\theta(\sum_{u \in V}Adj(u)) = O(|E|)\).</li>
<li>Hi ha el cost de les inicialitzacions, que &eacute;s&nbsp;\(O(n)\).</li>
</ol>
<p>En total, el cost del recorregut en amplada &eacute;s&nbsp;\(O(n + m) = O(|V| + |E|)\).</p>
<h5 style="margin-top: 0.4em;">Cost del recorregut en profunditat</h5>
<ol>
<li>El bucle exterior es fa&nbsp;\(\theta(|V|)\) vegades.</li>
<li>Per cada iteraci&oacute;, el bucle interior es fa per tots els adjacents a cada v&egrave;rtex amb un cost \(\theta(1)\). En total, el cost &eacute;s&nbsp;\(\theta(|E|)\).</li>
<li>El cost de les inicialitzacions &eacute;s&nbsp;\(O(n)\).</li>
</ol>
<p>En total, el cost del recorregut en profunditat &eacute;s&nbsp;\(\theta(|V| + |E|)\).</p>
<h5 style="margin-top: 0.4em;">Cost de l&#39;ordenaci&oacute; topol&ograve;gica</h5>
<p>&Eacute;s igual al cost del recorregut en profunditat.</p>
<h5 style="margin-top: 0.4em;">Cost de l&#39;algorisme de Dijkstra</h5>
<ul>
<li>Sense fer servir cues de prioritat:<br />
		Per a cada v&egrave;rtex que s&#39;afegeix al conjunt soluci&oacute; el cost en temps &eacute;s \(O(n)\) en cas pitjor. Com que s&#39;hi han d&#39;afegir els&nbsp;\(n\) v&egrave;rtexs del grup, en total el cost &eacute;s&nbsp;\(O(n^2)\).</li>
<li>Fent servir cues de prioritat per guardar les arestes/arcs:<br />
		A cada pas afegim un nou element al conjunt soluci&oacute;, tret de la cua de prioritats, amb cost&nbsp;\(log n + (log n) Adj(v)\). En total:&nbsp;\(O((n + m) log n)\).</li>
</ul>
<h4>Enlla&ccedil;os rellevants</h4>
<ul>
<li><a href="http://www.lsi.upc.edu/~ada/apunts/GV/ada-slides-4.pdf">ADA: Algorismes sobre grafs</a>, per Gabriel Valiente.</li>
<li><a href="http://ca.wikipedia.org/wiki/Graf">Article sobre grafs</a> a la Viquip&egrave;dia.</li>
</ul>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/eda-calcul-cost-algorismes/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs'>Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs</a> <small>Introducci&oacute; Els algorismes s&oacute;n per tot arreu i per aix&ograve;...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-diccionaris/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Diccionaris'>Apunts d&#8217;Estructures de Dades i Algorismes: Diccionaris</a> <small>Introducci&oacute; S&oacute;n un tipus abstracte de dades (TAD), &eacute;s a...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-dividir-i-vencer/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer'>Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer</a> <small>Introducci&oacute; L&#39;esquema de programaci&oacute; de dividir i v&egrave;ncer &eacute;s una...</small></li>
</ol></p> <p><a href="http://bloc.eurion.net/?flattrss_redirect&amp;id=1103&amp;md5=ba33cbee89e33cf613cdfd7ecc5b60c1" title="Flattr" target="_blank"><img src="http://bloc.eurion.net/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/eda-grafs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apunts d&#8217;Estructures de Dades i Algorismes: Diccionaris</title>
		<link>http://bloc.eurion.net/archives/2011/eda-diccionaris/</link>
		<comments>http://bloc.eurion.net/archives/2011/eda-diccionaris/#comments</comments>
		<pubDate>Mon, 10 Jan 2011 22:28:53 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[algorithmics]]></category>
		<category><![CDATA[eda]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=1079</guid>
		<description><![CDATA[Introducci&#243; S&#243;n un tipus abstracte de dades (TAD), &#233;s a dir, un conjunt d&#39;elements i un conjunt d&#39;operacions sobre ells. Un diccionari &#233;s un conjunt d&#39;elements amb una clau associada (treta d&#39;un conjunt amb un ordre total definit) amb les operacions de cercar, inserir i esborrar un element. Una estructura de dades &#233;s una estructura [...]]]></description>
			<content:encoded><![CDATA[<h4>Introducci&oacute;</h4>
<p>S&oacute;n un <strong>tipus abstracte de dades</strong> (TAD), &eacute;s a dir, un conjunt d&#39;elements i un conjunt d&#39;operacions sobre ells.</p>
<p>Un <strong>diccionari</strong> &eacute;s un conjunt d&#39;elements amb una clau associada (treta d&#39;un conjunt amb un ordre total definit) amb les operacions de cercar, inserir i esborrar un element.</p>
<p>Una <strong>estructura de dades</strong> &eacute;s una estructura que ens permet implementar TAD.</p>
<h4>Implementacions de diccionaris</h4>
<h5 style="margin-top: 1em;">1) Taules (no ordenades)</h5>
<ul>
<li>Inserir un element nou: \(\theta(1)\).</li>
<li>Esborrar un element: cost de cercar l&#39;element (\(O(n)\)) + cost de treure&#39;l de la taula (varia segons el mecanisme d&#39;eliminaci&oacute;, possiblement \(O(n)\)).</li>
</ul>
<h5>2) Llistes (enlla&ccedil;ades, encadenades)</h5>
<p>Per rec&oacute;rrer una llista s&#39;ha de fer de forma seq&uuml;encial, mitjan&ccedil;ant <strong>iteradors</strong> (punters).</p>
<p><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/Llista-encadenada.png"><img alt="" class="aligncenter size-medium wp-image-1080" height="36" src="http://bloc.eurion.net/wp-content/uploads/2011/01/Llista-encadenada-300x36.png" title="Llista encadenada" width="300" /></a></p>
<ul>
<li>Inserir un element nou:<br />
		&nbsp;&nbsp;- al principi: \(\theta(1)\);<br />
		&nbsp;&nbsp;- al final de la llista, recorrent-la sencera:&nbsp;\(\theta(n)\).</li>
<li>Cercar un element:&nbsp;\(O(n)\)</li>
<li>Esborrar un element: \(O(n)\)</li>
</ul>
<h5>3) Taules de dispersi&oacute; (<em>hash tables</em>)</h5>
<p><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/Taula-de-dispersió.png"><img alt="" class="aligncenter size-medium wp-image-1086" height="155" src="http://bloc.eurion.net/wp-content/uploads/2011/01/Taula-de-dispersió-300x155.png" title="Taula de dispersió" width="300" /></a></p>
<p>El disseny de la funci&oacute; de <em>hash</em> &eacute;s molt important per obtenir taules ben equilibrades.</p>
<p>En cas pitjor, el cost ser&agrave; de \(\theta(n)\), inserint al final amb una funci&oacute; de dispersi&oacute; que resulti en llistes llargues. Per&ograve;, si la funci&oacute; de dispersi&oacute; est&agrave; ben dissenyada, repartir&agrave; els elements equitativament, resultant llistes de mitjana \(\alpha = \frac{n}{M}\) amb un cost \(\theta(\alpha)\).</p>
<p><span id="more-1079"></span></p>
<h5>4) Arbres binaris de cerca (ABC, o <em>Binary Search Tree</em>, BST)</h5>
<p><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/Arbre-binari-de-cerca-1.png"><img alt="" class="alignleft size-thumbnail wp-image-1097" height="150" src="http://bloc.eurion.net/wp-content/uploads/2011/01/Arbre-binari-de-cerca-1-150x150.png" style="float: right; margin-left: 5px;" title="Arbre binari de cerca (1)" width="150" /></a></p>
<p>Un ABC &eacute;s un arbre binari on cada node t&eacute; una clau associada i els sub-arbres esquerra i dret compleixen les seg&uuml;ents propietats:</p>
<ol>
<li>\(\forall\) clau \(y\) associada a un node del sub-arbre esquerra d&#39;un node amb clau \(x\) es compleix que \(y &lt; x\).</li>
<li>\(\forall\) clau \(y\) associada a un node del sub-arbre dret d&#39;un node amb clau \(x\) es compleix que \(y &gt; x\).</li>
</ol>
<p>Observacions:</p>
<ol>
<li>Suposem que totes les claus s&oacute;n diferents.</li>
<li>Un arbre buit &eacute;s per definici&oacute; un ABC.</li>
</ol>
<ul>
<li>Construir un ABC a partir d&#39;un arbre buit i un conjunt d&#39;\(n\) claus:<br />
		&nbsp;&nbsp;- cas millor: \(\theta(n log n)\) (arbre equilibrat);<br />
		&nbsp;&nbsp;- cas mitj&agrave;: \(\theta(n log n)\), suposant que totes les permutacions de les&nbsp;\(n\) claus s&oacute;n igualment probables;<br />
		&nbsp;&nbsp;- cas pitjor:&nbsp;\(\theta(n^2)\) (ordenats).</li>
<li>Inserir una clau en un arbre d&#39;\(n\) nodes:&nbsp;\(\theta(h)\), on&nbsp;\(h\) &eacute;s l&#39;al&ccedil;ada de l&#39;arbre.<br />
		\(h = \begin{cases}n &amp; \small en\ cas\ pitjor \\ log n &amp; \small en\ el\ cas\ millor\ i\ mitj\grave{a}\end{cases}\)</li>
<li>Cercar una clau en un arbre d&#39;al&ccedil;ada&nbsp;\(h\):&nbsp;\(\theta(h)\).</li>
<li>Esborrar:<br />
		<img alt="" class="alignleft size-thumbnail wp-image-1093" height="150" src="http://bloc.eurion.net/wp-content/uploads/2011/01/Arbre-binari-de-cerca-3-150x150.png" style="float: left; margin-right: 5px;" title="Arbre binari de cerca (3)" width="150" />&nbsp;- Esborrar el 9: esborrar un fulla; &eacute;s f&agrave;cil.<br />
		&nbsp;- Esborrar el 7: esborrar un node amb un sub-arbre buit, &eacute;s f&agrave;cil.<br />
		&nbsp;- Esborrar l&#39;11: cal substituir-lo pel m&iacute;nim del sub-arbre dret (o b&eacute; pel m&agrave;xim del sub-arbre esquerra).</p>
<p style="clear: both;">&nbsp;</p>
</li>
</ul>
<h4>Arbres AVL (Adel&#39;son-Vel&#39;sk&icirc;i-Landis)</h4>
<p>Un arbre <strong>AVL</strong>&nbsp;&eacute;s un arbre binari de cerca tal que per tot node l&#39;al&ccedil;ada del seu seu-arbre esquerre no difereix en m&eacute;s d&#39;una unitat que l&#39;al&ccedil;ada del seu sub-arbre dret.</p>
<ul>
<li>Cercar una clau: algorisme id&egrave;ntic al dels ABC i de cost \(O(log n)\).</li>
<li>Inserir una clau: es fa servir el mateix algorisme dels ABC i despr&egrave;s, si la propietat de les al&ccedil;ades ja no &eacute;s certa, es reestructura l&#39;arbre per tal que torni a ser un arbre AVL.<br />
		Per tal de dur a terme la reestructuraci&oacute;, cada node ha de contenir informaci&oacute; de la seva al&ccedil;ada. A m&eacute;s, definim el concepte de <strong>factor d&#39;equilibri</strong>, com a l&#39;al&ccedil;ada del sub-arbre esquerra menys l&#39;al&ccedil;ada del sub-arbre dret; per ser \({-1, 0, 1}\). Al fer una inserci&oacute;, el primer node en tenir un mal factor d&#39;equilibri (&eacute;s a dir, de valor absolut superior a 1) &eacute;s el <strong>node cr&iacute;tic</strong>&nbsp;i &eacute;s on caldr&agrave; fer una <strong>rotaci&oacute;</strong>. Podem trobar-nos amb quatre casos:</p>
<ul style="margin-bottom: 0.4em;">
<li>Inserci&oacute; al sub-node esquerre del sub-node esquerre del node cr&iacute;tic (cas LL, <em>left-left</em>): cal fer una rotaci&oacute; simple.</li>
<li>Inserci&oacute; al sub-node dret del sub-node esquerre del node cr&iacute;tic (cas LR): cal fer una rotaci&oacute; doble.</li>
<li>Inserci&oacute; al sub-node esquerre del sub-node dret del node cr&iacute;tic (cas RL): cal fer una rotaci&oacute; doble.</li>
<li>Inserci&oacute; al sub-node dret del sub-node dret del node cr&iacute;tic (cas RR): cal fer una rotaci&oacute; doble.</li>
</ul>
<p>		El cost d&#39;una inserci&oacute; &eacute;s \(\theta(h)\) (on h &eacute;s l&#39;al&ccedil;ada de l&#39;abre,&nbsp;\(h = \theta(log n)\)) i el d&#39;una rotaci&oacute; &eacute;s \(\theta(1)\).</li>
<li>Esborrar una clau: poden caldre fins a \(log n\) passos per a rebalancejar l&#39;arbre.</li>
</ul>
<h4>Cues de prioritat</h4>
<p>Es creen en temps \(O(n)\) amb l&#39;algorisme <strong><em>heapify</em></strong>; s&oacute;n un arbre que compleix la propietat que la clau de tot node &eacute;s inferior o igual a la clau del node pare.</p>
<ul>
<li>Crear una cua de prioritats: \(O(n)\).</li>
<li>Consultar-ne el valor m&iacute;nim o m&agrave;xim: \(\theta(1)\).</li>
<li>Esborrar-ne el valor m&iacute;nim o m&agrave;xim: \(\theta(log n)\).</li>
<li>Inserir un element: \(O(log n)\).</li>
</ul>
<h4>Tipus abstractes de dades de la llibreria est&agrave;ndard de C++</h4>
<table style="margin-top: 0.5em;">
<tbody>
<tr>
<td><strong>&lt;stack&gt;</strong></td>
<td>push, pop, top, size, empty</td>
<td><abbr title="Last in, first out">LIFO</abbr></td>
</tr>
<tr>
<td><strong>&lt;queue&gt;</strong></td>
<td>push, pop, front, size, empty</td>
<td><abbr title="First in, first out">FIFO</abbr></td>
</tr>
<tr>
<td><strong>priority_queue</strong></td>
<td>push, pop, top, size, empty</td>
<td>ordenada</td>
</tr>
<tr>
<td><strong>pair</strong></td>
<td colspan="2">Amb <em>&lt;utility&gt;</em>, proporciona operadors (==, &gt;=, &lt;=, etc.) sobrecarregats per a parells de dades.</td>
</tr>
<tr>
<td><strong>&lt;set&gt;</strong></td>
<td colspan="2">cost d&#39;inserci&oacute;: \(O(log n)\)<br />
				<em>begin</em> &rarr; de tipus <em>set&lt;&#8230;&gt;::iterator</em><br />
				<em>end</em> &rarr; &iacute;dem, referencia l&#39;element seg&uuml;ent a l&#39;&uacute;ltim</td>
</tr>
</tbody>
</table>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/eda-grafs/' rel='bookmark' title='Apunts d’Estructures de Dades i Algorismes: Grafs'>Apunts d’Estructures de Dades i Algorismes: Grafs</a> <small>Definici&oacute; i propietats Graf: Graf dirigit (digraf): Un cam&iacute; de...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-dividir-i-vencer/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer'>Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer</a> <small>Introducci&oacute; L&#39;esquema de programaci&oacute; de dividir i v&egrave;ncer &eacute;s una...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-calcul-cost-algorismes/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs'>Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs</a> <small>Introducci&oacute; Els algorismes s&oacute;n per tot arreu i per aix&ograve;...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/eda-diccionaris/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer</title>
		<link>http://bloc.eurion.net/archives/2011/eda-dividir-i-vencer/</link>
		<comments>http://bloc.eurion.net/archives/2011/eda-dividir-i-vencer/#comments</comments>
		<pubDate>Sun, 09 Jan 2011 21:42:32 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[algorithmics]]></category>
		<category><![CDATA[eda]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=979</guid>
		<description><![CDATA[Introducci&#243; L&#39;esquema de programaci&#243; de dividir i v&#232;ncer &#233;s una t&#232;cnica per a resoldre problemes que consisteix en dividir el problema original en subproblemes (m&#233;s petits), resoldre els subproblemes i finalment combinar les solucions en una sola que resolgui el problema original. Mitjan&#231;ant aquest t&#232;cnica sovint obtenim una soluci&#243; recursiva. Exemples Cerca dicot&#242;mica: Exponenciaci&#243; r&#224;pida: [...]]]></description>
			<content:encoded><![CDATA[<h4>Introducci&oacute;</h4>
<p>L&#39;esquema de programaci&oacute; de <strong>dividir i v&egrave;ncer</strong> &eacute;s una t&egrave;cnica per a resoldre problemes que consisteix en dividir el problema original en subproblemes (m&eacute;s petits), resoldre els subproblemes i finalment combinar les solucions en una sola que resolgui el problema original. Mitjan&ccedil;ant aquest t&egrave;cnica sovint obtenim una soluci&oacute; recursiva.</p>
<h4>Exemples</h4>
<ol>
<li style="margin-bottom: 0.7em;">Cerca dicot&ograve;mica: \(T(n) = O(log n)\)</li>
<li style="margin-bottom: 0.7em;">Exponenciaci&oacute; r&agrave;pida: \(T(n) = \theta(log n)\)<br />
		\(x^n = \begin{cases}1 &amp; n = 0 \\ (x^2)^{\frac{n}{2}} &amp; n \gt 0, n\ \acute{e}s\ parell \\ x \cdot (x^2)^{\left\lfloor \frac{n}{2} \right\rfloor} &amp; n \gt 0, n\ \acute{e}s\ senar\end{cases}\)</li>
<li style="margin-bottom: 0.7em;"><em>Merge sort</em>: \(T(n) = \theta(n log n)\)</li>
<li style="margin-bottom: 0.7em;"><em>Quick s</em><em>ort</em> (inventat el 1960 per Hoare): \(T(n) = \begin{cases}\small cas\ millor: &amp; 2T(\frac{n}{2}) + \theta(n) &amp; \rightarrow \theta(n log n) \\ \small cas\ mitj\grave{a}: &amp; \frac{1}{n}\sum_{i=1}^{n}T(i) + T(n-i) + \theta(n) &amp; \Rightarrow \theta(n log n) \\ \small cas\ pitjor: &amp; c + T(n &#8211; 1) + \theta(n) &amp; \Rightarrow \theta(n^2)\end{cases}\)
<p>		Consististeix en agafar un pivot \(x\) i dividir l&#39;entrada en aquells elements \(\le x\) i aquells \(\ge x\), i repetir aquest procediment de forma recursiva en els dos grups. En la definici&oacute; de \(T(n)\), \(i\) representa el nombre d&#39;elements \(\le x\) i dep&egrave;n del pivot.</p>
<p><img alt="" class="aligncenter size-medium wp-image-1036" height="154" src="http://bloc.eurion.net/wp-content/uploads/2011/01/Algorisme-quick-sort-300x154.png" title="Algorisme quick sort" width="300" /></p>
<p><small>Nota: La llibreria est&agrave;ndard de C++ disposa d&#39;una implementaci&oacute; de l&#39;algorisme <em>Introsort</em>, que ordena amb q<em>uick sort</em> per&ograve; compta el nombre de crides recursives. A partir d&#39;un cert nombre \(c_{2} \cdot log n\) canvia a <em>heap sort</em>.</small></p>
</li>
<li style="margin-bottom: 0.7em;"><em>Quick Select</em> (selecci&oacute; del \(k\)-&egrave;ssim element d&#39;una taula desordenada)
\(T(n) = \begin{cases}\small cas\ millor\ i\ mitj\grave{a}: &amp; s(n) = s(\frac{n}{2}) + \theta(n) &amp; \Rightarrow \theta(n) \\ \small cas\ pitjor: &amp; s(n) = s(n &#8211; 1) + \theta(n) &amp; \Rightarrow \theta(n^2)\end{cases}\)
<p>Consisteix en agafar un pivot \(x\), fer la partició i trobar la posici&oacute; \(q\)&nbsp;de l&#39;element de m&eacute;s a la dreta del primer grup. Si \(q = k\) llavors ja hem acabat (el \(k\)-&egrave;ssim &eacute;s l&#39;element \(T[q]\)); si \(q \lt k\) cerquem l&#39;element \(k &#8211; q\) al segon grup; finalment, si \(q \gt k\), cerquem l&#39;element \(k\)-&egrave;ssim a T1.</p>
<p>			<small>Nota: existeix un altre algorisme de selecci&oacute; en temps <span style="text-decoration: underline;">lineal</span> en el cas pitjor: Floyd-Wilson.</small></p>
</li>
<li style="margin-bottom: 0.7em;">Algorisme de Karasuba (per a multiplicar)
<p>L&#39;algorisme per a multiplicar cl&agrave;ssic du a terme \(O(n^2)\) operacions. L&#39;algorisme de Karatsuba &eacute;s m&eacute;s r&agrave;pid per a nombres molt grans.</p>
<p>Sense p&egrave;rdua de generalitat: suposem nombres binaris, de la mateixa longitud i sent aquesta longitud una pot&egrave;ncia de 2. Per exemple, x = [a|b], y = [c|d].<br />
			\((a \cdot 2^{\frac{n}{2}} + b) (c \cdot 2^{\frac{n}{2}} + d) = x \cdot y\)<br />
			\(u = (a+b) (c+d)\ \ \ \ v = a \cdot c\ \ \ \ w = b \cdot d\)<br />
			\(x \cdot y = v \cdot 2^n + (u &#8211; v &#8211; w) \cdot 2^(\frac{n}{2}) + w\)</p>
\(T(n) = 3T(\frac{n}{2}) + \theta(n) \Rightarrow T(n) = \theta(n^{log_{2}3 \simeq 1.585})\)
</li>
</ol>
<p>Alguns apunts addicionals:</p>
<ul>
<li>El <em>merge sort</em>&nbsp;(implementat correctament) &eacute;s un algorisme d&#39;ordenaci&oacute; estable, amb el <em>quick sort</em> aquest no &eacute;s el cas.</li>
<li>L&#39;algorisme <em>quick sort </em>cau en el seu temps pitjor quan l&#39;entrada ja est&agrave; ordenada.</li>
</ul>
<h4>Implementaci&oacute; del quick sort</h4>

<div class="wp_syntax"><div class="code"><pre class="cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> partició<span style="color: #000080;">&lt;</span>vector<span style="color: #000080;">&lt;</span>elem<span style="color: #000080;">&gt;</span><span style="color: #000040;">&amp;</span> v, <span style="color: #0000ff;">int</span> e, <span style="color: #0000ff;">int</span> d<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #666666;">// Hoare</span>
    Elem x <span style="color: #000080;">=</span> v<span style="color: #008000;">&#91;</span>e<span style="color: #008000;">&#93;</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> e <span style="color: #000040;">-</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">int</span> j <span style="color: #000080;">=</span> d <span style="color: #000040;">+</span> <span style="color: #0000dd;">1</span><span style="color: #008080;">;</span>
    <span style="color: #0000ff;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">true</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">while</span> <span style="color: #008000;">&#40;</span>v<span style="color: #008000;">&#91;</span><span style="color: #000040;">--</span>j<span style="color: #008000;">&#93;</span> <span style="color: #000080;">&gt;</span> x<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">while</span> <span style="color: #008000;">&#40;</span>v<span style="color: #008000;">&#91;</span><span style="color: #000040;">++</span>i<span style="color: #008000;">&#93;</span> <span style="color: #000080;">&lt;</span> x<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>i <span style="color: #000080;">&gt;=</span> j<span style="color: #008000;">&#41;</span> <span style="color: #0000ff;">return</span> j<span style="color: #008080;">;</span>
        swap <span style="color: #008000;">&#40;</span>v<span style="color: #008000;">&#91;</span>i<span style="color: #008000;">&#93;</span>, v<span style="color: #008000;">&#91;</span>j<span style="color: #008000;">&#93;</span><span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
<span style="color: #0000ff;">void</span> quicksort<span style="color: #008000;">&#40;</span>vector<span style="color: #000080;">&lt;</span>elem<span style="color: #000080;">&gt;</span><span style="color: #000040;">&amp;</span> v, <span style="color: #0000ff;">int</span> e, <span style="color: #0000ff;">int</span> d<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>e <span style="color: #000080;">&lt;</span> d<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0000ff;">int</span> p <span style="color: #000080;">=</span> partició<span style="color: #008000;">&#40;</span>v, e, d<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        quicksort<span style="color: #008000;">&#40;</span>v, e, p<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
        quicksort<span style="color: #008000;">&#40;</span>v, p<span style="color: #000040;">+</span><span style="color: #0000dd;">1</span>, e<span style="color: #008000;">&#41;</span><span style="color: #008080;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<h4>Enllaços rellevants</h4>
<ul>
<li><em><a href="http://www.lsi.upc.edu/~duch/home/duch/dyd.pdf">Esquema de Dividir y Vencer</a></em>, Amalia Duch.</li>
<li><a href="http://en.wikipedia.org/wiki/Merge_sort">Merge sort</a> i <a href="http://en.wikipedia.org/wiki/Quick_sort">Quick sort</a>, Wikipedia.</li>
<li><a href="http://goanna.cs.rmit.edu.au/~stbird/Tutorials/QuickSelect.html">Explicació i exemple interactiu del QuickSelect</a>.</li>
</ul>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/eda-calcul-cost-algorismes/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs'>Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs</a> <small>Introducci&oacute; Els algorismes s&oacute;n per tot arreu i per aix&ograve;...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-programacio-dinamica/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Programació dinàmica'>Apunts d&#8217;Estructures de Dades i Algorismes: Programació dinàmica</a> <small>1. Nombres de Fibonacci L&#39;algorisme trivial per al c&agrave;lcul dels...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-diccionaris/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Diccionaris'>Apunts d&#8217;Estructures de Dades i Algorismes: Diccionaris</a> <small>Introducci&oacute; S&oacute;n un tipus abstracte de dades (TAD), &eacute;s a...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/eda-dividir-i-vencer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apunts d&#8217;Estructures de Dades i Algorismes: Càlcul de costs</title>
		<link>http://bloc.eurion.net/archives/2011/eda-calcul-cost-algorismes/</link>
		<comments>http://bloc.eurion.net/archives/2011/eda-calcul-cost-algorismes/#comments</comments>
		<pubDate>Sun, 09 Jan 2011 17:30:32 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[algorithmics]]></category>
		<category><![CDATA[eda]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[universitat]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=913</guid>
		<description><![CDATA[Introducci&#243; Els algorismes s&#243;n per tot arreu i per aix&#242; volem analitzar-ne les caracter&#237;stiques. Algunes de les caracter&#237;stiques m&#233;s importants dels algorismes s&#243;n: correctesa! senzillesa escalabilitat modularitat efici&#232;ncia fiabilitat etc. Nosaltres en concret en mirarem l&#39;efici&#232;ncia i l&#39;&#250;s dels recursos del sistema a nivell te&#242;ric, &#233;s a dir, el temps d&#39;execuci&#243;, la quantitat de mem&#242;ria [...]]]></description>
			<content:encoded><![CDATA[<h4>Introducci&oacute;</h4>
<p>Els <strong>algorismes</strong> s&oacute;n per tot arreu i per aix&ograve; volem analitzar-ne les caracter&iacute;stiques. Algunes de les caracter&iacute;stiques m&eacute;s importants dels algorismes s&oacute;n:</p>
<ul id="eda_algorithm_characteristics">
<li style="float: left; width: 25%;">correctesa!</li>
<li style="float: left; width: 25%;">senzillesa</li>
<li style="float: left; width: 25%;">escalabilitat</li>
<li style="float: left; width: 25%;">modularitat</li>
<li style="float: left; width: 25%;">efici&egrave;ncia</li>
<li style="float: left; width: 25%;">fiabilitat</li>
<li style="float: left; width: 25%;">etc.</li>
</ul>
<p><br style="clear: both;" /><br />
	Nosaltres en concret en mirarem l&#39;<strong>efici&egrave;ncia</strong> i l&#39;&uacute;s dels recursos del sistema a nivell te&ograve;ric, &eacute;s a dir, el temps d&#39;execuci&oacute;, la quantitat de mem&ograve;ria que utilitzen, etc.</p>
<hr />
<p>Suposarem que el cost de totes les operacions elementals &eacute;s constant, i anomenem &laquo;<strong>n</strong>&raquo; la mida de l&#39;entrada, en funci&oacute; de la qual veurem el cost en temps i mem&ograve;ria dels algorismes.</p>
<p><strong>Def.</strong> Donat un algorisme A, amb conjunt d&#39;entrades \(\vartheta\), el seu cost (efici&egrave;ncia) &eacute;s una funci&oacute;: \(\begin{array}{ll}T: &amp; \vartheta \rightarrow \mathbb{R}^{+} \\ &amp; \alpha \mapsto T(\alpha)\end{array}\)</p>
<p>Per facilitar la manipulaci&oacute; de cost restringim el conjunt \(\vartheta\) al conjunt \(\vartheta_{n}\), que correspon al de totes les entrades de mida \(n \in \mathbb{R}\).</p>
<p><strong>Def.</strong> Donat un algorisme A, amb un conjunt d&#39;entrades de mida n (\(\vartheta_{n}\)), el cost d&#39;A en el cas millor, pijtor i mitj&agrave; &eacute;s:</p>
<ul>
<li>\(T_{millor}(n) = min\left\{T_{n}(\alpha) | \alpha \in \vartheta_{n}\right\}\)</li>
<li>\(T_{pitjor}(n) = max\left\{T_{n}(\alpha) | \alpha \in \vartheta_{n}\right\}\)</li>
<li>\(T_{mitj\grave{a}}(n) = \sum_{\alpha \in \vartheta_{n}} Pr(\alpha) \cdot T_{n}(\alpha)\)<br />
		(suposant un coneixement de la distribuci&oacute; estad&iacute;stica de les entrades)</li>
</ul>
<p>Observacions:</p>
<ul>
<li>\(T_{millor}(n) \le T_{n}(\alpha) \le T_{pitjor}(n)\)</li>
<li>\(T_{millor}(n) \le T_{mitj\grave{a}}(n) \le T_{pitjor}(n)\)</li>
</ul>
<p><span id="more-913"></span></p>
<h4>Notaci&oacute; asimpt&ograve;tica</h4>
<p>Considerem funcions del tipus \(f: \mathbb{N} \rightarrow \mathbb{N}\). Definim:</p>
<ul>
<li>\(O(f) = \left\{g: \mathbb{N} \rightarrow \mathbb{N}, \exists n_0 \ge 0, \forall n \ge n_{0}: g(n) \le f(n) \cdot c_{0}\right\}\) \(g \in O(f) \Leftrightarrow\) &laquo;\(g\) creix m&eacute;s a poc a poc o igual que \(f\)&raquo; (per a valors prou grans i ignorant les pendents)</li>
</ul>
<ul>
<li>\(\Omega(f) = \left\{g: \mathbb{N} \rightarrow \mathbb{N}, \exists n_0 \ge 0, \forall n \ge n_{0}: g(n) \ge f(n) \cdot c_{0}\right\}\) \(g \in \Omega(f) \Leftrightarrow\) &laquo;\(g\) creix m&eacute;s r&agrave;pid o igual que \(f\)&raquo;</li>
</ul>
<ul>
<li>\(\theta(f) = O(f) \cap \Omega(f)\) \(g \in \Omega(f) \Leftrightarrow\) &laquo;\(g\) creix igual que \(f\)&raquo; (en altres paraules, \(g\) i \(f\) tenen el mateix ordre de creixement)</li>
</ul>
<p>Considerant \(g: \mathbb{N} \rightarrow \mathbb{R}^{+}\) les definicions serien similars.</p>
<h4>Propietats</h4>
<ul>
<li>
<ul style="list-style-type: none;">
<li>\(\lim_{n \to \infty} \frac{f(n)}{g(n)} \lt +\infty \Rightarrow f \in O(g)\)</li>
<li>\(\lim_{n \to 0} \frac{f(n)}{g(n)} \gt 0 \Rightarrow f \in \Omega(g)\)</li>
<li>\(\lim_{n \to \infty} \frac{f(n)}{g(n)} \in (0, \infty) \Rightarrow f \in \theta(g)\)</li>
<li>Nota: <a href="http://ca.wikipedia.org/wiki/Regla_de_L'H%C3%B4pital">Regla de L&#39;H&ocirc;pital</a>.</li>
</ul>
</li>
<li>Reflexivitat: \(f \in O(f)\) (&iacute;dem per a \(\Omega\) i \(\theta\))</li>
<li>Transitivitat: \(f \in O(g) \land g \in O(h) \Rightarrow f \in O(h)\) (semblant per a \(\Omega\) i \(\theta\))</li>
<li>Regles de c&agrave;lcul:
<ul style="list-style-type: none;">
<li>\(O(f) = O(f \cdot c) \forall c \gt 0 ct.\)</li>
<li>\(O(f) + O(g) = O(f + g) = O\left(m\grave{a}x\{f, g\}\right)\)</li>
<li>\(O(f) \cdot O(g) = O(f \cdot g)\)</li>
<li>(&iacute;dem per a \(\Omega\) i \(\theta\))</li>
</ul>
</li>
</ul>
<h4>Convenci&oacute;</h4>
<p>Per convenci&oacute; es fa un ab&uacute;s del llenguatge i sovint escrivim \(f = O(g)\) quan realment volem dir \(f \in O(g)\). (Cal tenir en compte aix&ograve; a l&#39;utilitzar la propietat de transitivitat!) Per exemple:</p>
<ul>
<li>\(4n = O(n^2) = O(n^3)\) on realment hauria de ser \(\subseteq\)</li>
<li>\(2n = O(n)\)</li>
</ul>
<h4>Funcions de cost</h4>
<p>En general, tenim un algorisme \(A\) amb un conjunt d&#39;entrades \(E\). Volem caracteritzar l&#39;&uacute;s d&#39;algun recurs quan s&#39;executa \(A\) sobre una entrada \(x \in E\).</p>
\(\begin{array}{ll}C_{A}: &amp; E \rightarrow \mathbb{N} \\ &amp; x \mapsto C_{A}(x)\end{array}\)
<p>Obtenir \(C_{A}(x)\) &eacute;s, en general, massa dif&iacute;cil \(\Rightarrow\) simplifiquem. No mirem cada entrada individual sin&oacute; que ajuntem totes les entrades de la mateixa talla. Anomenem \(|x|\) la talla d&#39;\(x\).</p>
<p>Estudiem els algorismes calculant el seu cost en funci&oacute; de la talla de les seves entrades. A m&eacute;s, nom&eacute;s mirarem els costos pitjor i millor (veure introducci&oacute;) i \(C_{mitj\grave{a}}(n) = \frac{1}{|E_{n}|} \sum_{x \in E_{n}} C_{A}(x)\) on \(E_{n} = \left\{x \in E \mid |x|= n\right\}\) (aquesta darrera funci&oacute; de cost &eacute;s dif&iacute;cil d&#39;obtenir i no t&eacute; en compte les probabilitats).</p>
\(\forall x \in E: c_{millor}(|x|) \le C_{A}(x) \le C_{pitjor}(|x|)\)
\(\forall n: c_{millor}(n) \le C_{mitj\grave{a}}(n) \le C_{pitjor}(n)\)
<p>Aix&iacute; doncs, en algor&iacute;smica calculem els costos dels algorismes donant fites (superiors i inferiors) en funci&oacute; de la talla de les entrades, utilitzant notaci&oacute; asimpt&ograve;tica.</p>
<h4>Cost d&#39;algorismes recursius</h4>
<p>El cost dels algorismes recursius s&#39;expressa generalment mitjan&ccedil;ant una <strong>equaci&oacute; recorrent</strong> (<strong>recurr&egrave;ncia</strong>). El cost de l&#39;algorisme ve donat per la soluci&oacute; a aquesta. Dos tipus de recurr&egrave;ncies freq&uuml;ents s&oacute;n les <strong>recurr&egrave;ncies substractores</strong> i les <strong>recurr&egrave;ncies divisores</strong>.</p>
<h5>Recurr&egrave;ncies substractores</h5>
<p>Les recurr&egrave;ncies substractores prenen la forma seg&uuml;ent:</p>
\(T(n) = \begin{cases}f(n) &amp; n \le k&#39; \\ a \cdot T(n &#8211; c) + g(n) &amp; n &gt; k&#39; \end{cases}\)
<p>On \(a\) &eacute;s una constant no negativa (\(a \ge 0\)), \(c\) &eacute;s una constant estrictament positiva (\(c \ \)) i \(g\) &eacute;s una funci&oacute; amb cost \(\theta(n^k)\).</p>
<p><strong>Teorema mestre I (per a recurr&egrave;ncies substractores)</strong></p>
<p>Donada la recurr&egrave;ncia anterior, trobem el cost segons: \(T(n) = \begin{cases}\theta(n^k) &amp; a &lt; 1 \\ \theta(n^{k+1}) &amp; a = 1 \\ \theta(a^{n/c}) &amp; a &gt; 1\end{cases}\)</p>
<h5 style="margin-top: 1.5em;">Recurr&egrave;ncies divisores</h5>
<p>Les recurr&egrave;ncies divisores prenen la seg&uuml;ent forma:</p>
\(T(n) = \begin{cases}f(n) &amp; n \le c&#39; \\ a \cdot T(\frac{n}{b}) + g(n) &amp; n &gt; c&#39; \end{cases}\)
<p>On \(a\) &eacute;s una constant no negativa (\(a \ge 0\)), \(b &gt; 1\) i \(g\) &eacute;s una funci&oacute; amb cost \(\theta(n^k)\).</p>
<p><strong>Teorema mestre II (per a recurr&egrave;ncies divisores)</strong></p>
<p>Sigui \(\alpha = log_{b}(a)\), i donada la recurr&egrave;ncia anterior, aleshores: \(T(n) = \begin{cases}\theta(n^k) &amp; \alpha &lt; k \\ \theta(n^{\alpha} \cdot log n) &amp; \alpha = k \\ \theta(n^{\alpha}) &amp; \alpha &gt; k\end{cases}\)</p>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/eda-dividir-i-vencer/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer'>Apunts d&#8217;Estructures de Dades i Algorismes: Dividir i Vèncer</a> <small>Introducci&oacute; L&#39;esquema de programaci&oacute; de dividir i v&egrave;ncer &eacute;s una...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-diccionaris/' rel='bookmark' title='Apunts d&#8217;Estructures de Dades i Algorismes: Diccionaris'>Apunts d&#8217;Estructures de Dades i Algorismes: Diccionaris</a> <small>Introducci&oacute; S&oacute;n un tipus abstracte de dades (TAD), &eacute;s a...</small></li>
<li><a href='http://bloc.eurion.net/archives/2011/eda-grafs/' rel='bookmark' title='Apunts d’Estructures de Dades i Algorismes: Grafs'>Apunts d’Estructures de Dades i Algorismes: Grafs</a> <small>Definici&oacute; i propietats Graf: Graf dirigit (digraf): Un cam&iacute; de...</small></li>
</ol></p> <p><a href="http://bloc.eurion.net/?flattrss_redirect&amp;id=913&amp;md5=c7f9a337ed8de6e13fa0b8e9a899b9f7" title="Flattr" target="_blank"><img src="http://bloc.eurion.net/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/eda-calcul-cost-algorismes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A list of some commercial GNU/Linux games</title>
		<link>http://bloc.eurion.net/archives/2011/a-list-of-some-commercial-gnulinux-games/</link>
		<comments>http://bloc.eurion.net/archives/2011/a-list-of-some-commercial-gnulinux-games/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 16:32:17 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Planet Ubuntu]]></category>
		<category><![CDATA[Planet Ubuntu.cat]]></category>
		<category><![CDATA[games]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=872</guid>
		<description><![CDATA[I thought I&#8217;d be nice to make a little list of some of the GNU/Linux games I&#8217;ve tried out this past year. I&#8217;ve tried to keep the list heterogeneous (different game genres, all from different producers, some freshly released and some quite older&#8230;). I&#8217;ve also decided to only include commercial games in this post; if [...]]]></description>
			<content:encoded><![CDATA[<p>I thought I&#8217;d be nice to make a little list of some of the GNU/Linux games I&#8217;ve tried out this past year. I&#8217;ve tried to keep the list heterogeneous (different game genres, all from different producers, some freshly released and some quite older&#8230;).</p>
<p>I&#8217;ve also decided to only include commercial games in this post; if it gets positive feedback I may also post a list of my favourite free games.</p>
<p>Anyway, here it goes:</p>
<table border="0">
<tbody>
<tr>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/vendetta-online.png"><img class="size-medium wp-image-873 aligncenter" title="Vendetta Online" src="http://bloc.eurion.net/wp-content/uploads/2011/01/vendetta-online-300x187.png" alt="" width="300" height="187" /></a></td>
<td><strong><a href="http://vendetta-online.com/">Vendetta Online</a></strong></p>
<p>A massively multiplayer online first-person space-combat game featuring possibilities in trading, mining, combat, warfare, piracy&#8230;</p>
<p>Price: $9.99 / month (free 8 hour trial)<br />
License: Proprietary</td>
</tr>
<tr>
<td><strong><a href="http://www.wolfire.com/lugaru">Lugaru HD</a></strong></p>
<p>A third-person action game featuring a rabbit on a fight to save his fellow rabbits from slavery in a fight against corrupt rabbits and wolves.</p>
<p>Price: $9.99<br />
License: Open-source <a href="http://hg.icculus.org/icculus/lugaru/">code</a>, proprietary data<br />
<em>Humble Indie Bundle #1</em></td>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/lugaru.png"><img class="aligncenter" title="Lugaru HD" src="http://bloc.eurion.net/wp-content/uploads/2011/01/lugaru-150x150.png" alt="" width="150" height="150" /></a></td>
</tr>
<tr>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/andyetitmoves.png"><img class="size-medium wp-image-883 aligncenter" title="And Yet It Moves" src="http://bloc.eurion.net/wp-content/uploads/2011/01/andyetitmoves-300x182.png" alt="" width="300" height="182" /></a></td>
<td><a href="http://www.andyetitmoves.net/"><strong>And Yet It Moves</strong></a></p>
<p>A platform game in a world of paper collage you can rotate at will, turning walls into floors, slides into platforms and moving stacks of rocks (or even enemies).</p>
<p>Price: $9.99 / 8.99€<br />
License: Proprietary</td>
</tr>
<tr>
<td><strong><a href="http://www.savage2.com/">Savage 2</a></strong></p>
<p>A fantasy first-person shooter, action role-playing game (in player role) and real-time strategy (in commander role) multiplayer game.</p>
<p>Price: Free / $9.99 (Premium Account)<br />
License: Proprietary</p>
<p>See also <a href="http://www.heroesofnewerth.com/"><strong>Heroes of Newerth</strong></a>, a fantasy strategy game inspired in DotA ($30).</td>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/savage2.jpg"><img class="size-thumbnail wp-image-886 aligncenter" title="Savage 2" src="http://bloc.eurion.net/wp-content/uploads/2011/01/savage2-150x150.jpg" alt="" width="150" height="150" /></a></td>
</tr>
<tr>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/enemy-territory-quake-wars.jpg"><img class="aligncenter size-medium wp-image-891" title="Enemy Territory: Quake Wars" src="http://bloc.eurion.net/wp-content/uploads/2011/01/enemy-territory-quake-wars-300x225.jpg" alt="" width="300" height="225" /></a></td>
<td><strong><a href="http://www.idsoftware.com/games/enemyterritory/etqw/">Enemy Territory: Quake Wars</a></strong></p>
<p>A futuristic, objective-driven and class-based multiplayer first person shooter featuring the fight between the Earth&#8217;s Global Defense Force and the alien Strogg.</p>
<p><a href="http://www.google.com/search?q=enemy+territory+quake+wars+pc&amp;tbs=shop:1">Available at shops</a><br />
License: Proprietary</td>
</tr>
<tr>
<td><strong><a href="http://www.penumbragame.com/">Penumbra</a> (Overture, Black Plague)</strong></p>
<p>A series of exploration-based horror games.</p>
<p>Price: 16.20€ (demo available)<br />
License: Open-source <a href="http://frictionalgames.blogspot.com/2010/05/penumbra-overture-goes-open-source.html">code</a>, proprietary data</p>
<p>See also <a href="http://www.amnesiagame.com/">Amnesia: The Dark Descent</a>.</td>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/penumbra-black-plague.jpg"><img class="aligncenter size-thumbnail wp-image-893" title="Penumbra: Black Plague" src="http://bloc.eurion.net/wp-content/uploads/2011/01/penumbra-black-plague-150x150.jpg" alt="" width="150" height="150" /></a></td>
</tr>
<tr>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/world-of-goo.png"><img class="aligncenter size-medium wp-image-895" title="World of Goo" src="http://bloc.eurion.net/wp-content/uploads/2011/01/world-of-goo-300x224.png" alt="" width="300" height="224" /></a></td>
<td><strong><a href="http://www.worldofgoo.com/">World of Goo</a></strong></p>
<p>A physics-based puzzle game. Truly a work of art.</p>
<p>Price: $20<br />
License: Proprietary<br />
<em>Humble Indie Bundle #1 </em></td>
</tr>
<tr>
<td><strong><a href="http://www.tycoongames.eu/adventures/bionicheart.php">Bionic Heart</a></strong></p>
<p>A science-fiction visual novel with interactive scenes (you can choose between different actions which change the ending of the story).</p>
<p>Price: 12.70€ + VAT (demo available)<br />
License: Proprietary</td>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/bionic-heart.png"><img class="aligncenter size-thumbnail wp-image-903" title="Bionic Heart" src="http://bloc.eurion.net/wp-content/uploads/2011/01/bionic-heart-150x150.png" alt="" width="150" height="150" /></a></td>
</tr>
<tr>
<td><a href="http://bloc.eurion.net/wp-content/uploads/2011/01/revenge-of-the-titans.jpg"><img class="aligncenter size-medium wp-image-896" title="Revenge of the Titans" src="http://bloc.eurion.net/wp-content/uploads/2011/01/revenge-of-the-titans-300x300.jpg" alt="" width="210" height="210" /></a></td>
<td><a href="http://www.puppygames.net/revenge-of-the-titans/"><strong>Revenge of the Titans</strong></a></p>
<p>A tower defense game with RTS elements.</p>
<p>Price: 10.66€ + VAT<br />
License: <a href="http://blog.wolfire.com/2010/12/Revenge-of-the-Titans-will-go-open-source-at-1-75M">Open-source code</a> (not yet available), proprietary data<br />
<em> Humble Indie Bundle #2</em></td>
</tr>
</tbody>
</table>
<p>There are many more GNU/Linux-compatible games out there. Check out the other <a href="http://www.humblebundle.com/">Humble Indie Bundle</a> games, for instance. You may also follow <a href="http://www.linuxgames.com/">LinuxGames</a> to keep up with the latest news.</p>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/debian-games-team-meeting/' rel='bookmark' title='Debian Games Team Meeting'>Debian Games Team Meeting</a> <small>This announcement was provided by Martin Erik Werner. I&#8217;m reproducing...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2011/a-list-of-some-commercial-gnulinux-games/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Apunts de Sistemes Operatius</title>
		<link>http://bloc.eurion.net/archives/2010/apunts-de-sistemes-operatius/</link>
		<comments>http://bloc.eurion.net/archives/2010/apunts-de-sistemes-operatius/#comments</comments>
		<pubDate>Sun, 14 Nov 2010 11:21:51 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[apunts]]></category>
		<category><![CDATA[fib]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[operating systems]]></category>
		<category><![CDATA[sistemes operatius]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=805</guid>
		<description><![CDATA[Introducció Un sistema operatiu és un programa que gestiona el maquinari d&#8217;un ordinador, proporciona una base per a d&#8217;altres programes i fa d&#8217;intermediari entre l&#8217;usuari de l&#8217;ordinador i el maquinari (fent així el seu ús més fàcil, eficient i segur). El primer sistema operatiu va ser creat el 1956 per General Motors, per a un [...]]]></description>
			<content:encoded><![CDATA[<h4>Introducció</h4>
<p>Un <a href="http://ca.wikipedia.org/wiki/Sistema_operatiu">sistema operatiu</a> és un programa que gestiona el maquinari d&#8217;un ordinador, proporciona una base per a d&#8217;altres <a title="application programs">programes</a> i fa d&#8217;intermediari entre l&#8217;usuari de l&#8217;ordinador i el maquinari (fent així el seu ús més fàcil, eficient i segur).</p>
<p>El <a href="http://en.wikipedia.org/wiki/History_of_operating_systems">primer</a> sistema operatiu va ser creat el 1956 per General Motors, per a un <em>mainframe</em> d&#8217;IBM. Per a més informació: <a href="http://www.psexam.com/Notes-for-Computer-Science/operating-systems-history-of-operating-system-article.html">History of Operating Systems</a>, per Ayman Moumina (<a href="http://www.computinghistorymuseum.org/teaching/papers/research/history_of_operating_system_moumina.pdf">versió PDF</a>).</p>
<h4>Crides a sistema</h4>
<p>El diagrama d&#8217;una crida a sistema és el següent:</p>
<table>
<tbody>
<tr>
<td style="color: green;" colspan="4">Mode d&#8217;usuari (<em>User Mode</em>)</td>
<td style="color: blue;">Mode privilegiat</td>
</tr>
<tr>
<td>Programa</td>
<td>Llibreria del llenguatge</td>
<td>Llibreria del sistema</td>
<td><em>Trap</em> (crida al sistema)</td>
<td>Codi del sistema operatiu</td>
</tr>
<tr>
<td></td>
<td><em>printf()</em></td>
<td><em>write()</em></td>
<td><em><a href="http://en.wikipedia.org/wiki/X86_assembly_language">x86</a>: INT 0x&#8230;</em></td>
<td></td>
</tr>
</tbody>
</table>
<p>El sistema disposa d&#8217;un vector anomenat <a href="http://en.wikipedia.org/wiki/Interrupt_descriptor_table">Interrupt Descriptor Table</a> (IDT) que determina la funció a invocar per a cada crida al sistema (o excepció per maquinari).</p>
<h4>Processos</h4>
<ul>
<li>Un <strong>procés</strong> és la unitat bàsica d&#8217;assignació de recursos i té com a mínim un <strong>fil</strong>.</li>
<li>Un <strong>fil</strong> (també <strong>flux</strong> o <strong><em>thread</em></strong>) és la unitat bàsica de planificació per a l&#8217;execució d&#8217;instruccions.</li>
</ul>
<p>Per defecte, els processos no comparteixen recursos (memòria, descriptors de fitxers ni fils) entre ells. Algunes de les seves propietats són el <strong>PID</strong> (identificador del procés) i en UNIX l&#8217;<strong>UID</strong> (usuari propietari) i el <strong>GID</strong> (grup propietari). En sistemes <a href="http://kernel.org/">Linux</a> també poden tenir <a title="«Personality», al final de la pàgina" href="http://www.win.tue.nl/~aeb/linux/lk/lk-3.html">personalitat</a>, el qual permet canviar el comportament d&#8217;algunes crides a sistema per motius de compatibilitat.</p>
<p>Al llarg de la seva vida un procés passa per diferents <a href="http://en.wikipedia.org/wiki/Process_states">estats</a>. En termes generals, aquests es poden representar amb el següent graf:</p>
<p><a href="http://bloc.eurion.net/wp-content/uploads/2010/11/estats_dels_processos.png"><img class="aligncenter size-full wp-image-820" title="Generalització dels possibles estats dels processos per al Sistema Operatiu" src="http://bloc.eurion.net/wp-content/uploads/2010/11/estats_dels_processos.png" alt="" width="778" height="231" /></a></p>
<p><span id="more-805"></span></p>
<p>El <a href="http://en.wikipedia.org/wiki/Process_control_block">Process Control Block</a> (PCB) emmagatzema la informació relativa a un procés, com ara els identificadors ja mencionats, l&#8217;estat, el <a href="http://en.wikipedia.org/wiki/Program_counter">PC</a>, el contingut dels registres l&#8217;últim cop que ha estat interromput, informació per a la gestió de memòria, la llista de fitxers oberts, estadístiques que el sistema operatiu consideri rellevants, procés pare i fills, així com altres dades (prioritat del procés, restriccions de memòria o fitxers, etc). Aquesta estructura de dades (anomenada <em>task_struct</em>, en Linux) és generada quan es crea el procés i no s&#8217;allibera fins que el procés mor i el seu pare (o, si aquest no existeix, l&#8217;<a href="http://en.wikipedia.org/wiki/Init">init</a>) el recull.</p>
<p>El sistema operatiu inclou funcions de comptabilitat (<em>accounting</em>) i cada «<em>tick</em>» (equivalent a un determinat nombre de cicles de rellotge) s&#8217;encarrega de decidir quin ha de ser el procés actiu.</p>
<p><strong>Alguns serveis relacionats amb els processos (Linux)</strong></p>
<table>
<tbody>
<tr>
<td style="font-weight: bold; white-space: nowrap;">pid_t fork();</td>
<td>Crea un procés fill que és una còpia idèntica del pare, però que n&#8217;és independent. (En sistemes Linux, només hereta un dels fils).</td>
</tr>
<tr>
<td style="font-weight: bold; white-space: nowrap;">void exit(int status);</td>
<td>Converteix el procés en <em>zombie</em> i li assigna el codi d&#8217;eixida indicat.</td>
</tr>
<tr>
<td style="font-weight: bold; white-space: nowrap;">pid_t wait(int *status);</td>
<td>Espera que un dels processos fills acabi i retorna el seu PID. Si <em>status</em> no és <em>NULL</em>, li assigna el codi d&#8217;eixida del fill.</td>
</tr>
<tr>
<td style="font-weight: bold; white-space: nowrap;">int execlp(char *path, &#8230;);</td>
<td>Substitueix l&#8217;executable del procés actual (és a dir, <em>muta el procés</em>). Aquesta crida només retorna en cas d&#8217;error.<br />
Exemple: <em>execlp(&#8220;/bin/ls&#8221;, &#8220;ls&#8221;, &#8220;-l&#8221;, NULL)</em></td>
</tr>
<tr>
<td></td>
<td>Veure també: <em><a href="http://en.wikipedia.org/wiki/Clone_(Linux_system_call)">clone</a></em>, <em><a href="http://en.wikipedia.org/wiki/POSIX_Threads">threads</a></em>.</td>
</tr>
</tbody>
</table>
<p><strong>Optimitzacions</strong><br />
Una possible optimització per millorar l&#8217;eficiència d&#8217;un <em>fork</em> és el <strong><em><a href="http://en.wikipedia.org/wiki/Copy-on-write">copy-on-write</a></em></strong> (COW), que consisteix en no duplicar la memòria del procés fins que un dels dos la vulgui modificar (així és especialment útil, per exemple, quan es clona un procés per <em>mutar</em>-lo tot seguit, ja que llavors s&#8217;evita del tot haver de copiar-ne la memòria).</p>
<h4>Fils (<em>threads</em>)</h4>
<p>Els <strong>fils</strong> són més ràpids de crear i destruir que processos sencers, i comparteixen memòria i descriptors de fitxers.</p>
<p>Per treballar amb ells utilitzem la API de <a href="http://en.wikipedia.org/wiki/POSIX_Threads">fils de POSIX</a>. Aquesta ens deixa manipular <strong>fils d&#8217;usuari</strong> que poden estar mapejats sobre <strong>fils del sistema</strong> (<em>kernel threads</em>) de forma molts-a-un, un-a-un o un-a-molts.</p>
<p>En el sistema Linux cada fil del sistema és identificat per un identificador <strong>LWP</strong> (<em><a href="http://en.wikipedia.org/wiki/Light-weight_process">Light-Weight Process</a></em>), el qual ens permet enviar-li senyal. Això no és així amb d&#8217;altres sistemes operatius (per exemple, algunes versions de <a href="http://en.wikipedia.org/wiki/Solaris_(operating_system)">Solaris</a>), els quals només permeten adreçar senyals a processos sencers.</p>
<p><strong>Problemes amb la concurrència</strong></p>
<p>En un programa <em>multi-thread</em> amb recursos compartits entre els diferents fils podem trobar-nos amb problemes (per exemple, si dos fils accedeixen a la mateixa variable alhora). Poden produir-se errors molt difícils d&#8217;identificar (<em><a href="http://ca.wikipedia.org/wiki/Situaci%C3%B3_de_competici%C3%B3">race conditions</a></em>).</p>
<p>La solució als problemes de concurrència és l&#8217;ús de <a href="https://computing.llnl.gov/tutorials/pthreads/#Mutexes">Mutex</a> (exclusió mútua o <em>locks</em>) per protegir les <strong>seccions crítiques</strong> del codi. Es poden implementar amb <a href="http://ca.wikipedia.org/wiki/Espera_activa">espera activa</a> (<em><a href="http://en.wikipedia.org/wiki/Busy_waiting">busy waiting</a></em>) o bé adormint el fil. Al implementar aquestes mesures cal evitar el problema de l&#8217;<strong><a href="http://ca.wikipedia.org/wiki/Abra%C3%A7ada_mortal">abraçada mortal</a></strong> (<em><a href="http://en.wikipedia.org/wiki/Deadlock">deadlock</a></em>).</p>
<p>L&#8217;API de <a href="http://en.wikipedia.org/wiki/POSIX">POSIX</a> ens proporciona les següents funcions útils:</p>
<ul>
<li><em>pthread_mutex_trylock</em>: intenta reservar un recurs i retorna indicant si ho ha aconseguit o no.</li>
<li><em>pthread_mutex_lock</em>: reserva un recurs (esperant que estigui lliure, si cal).</li>
<li><em>pthread_mutex_unlock</em>: allibera un recurs prèviament reservat.</li>
</ul>
<h4>Planificació</h4>
<p>Hem mencionat abans que cada <em>tick</em> el sistema operatiu s&#8217;encarrega de decidir quin procés s&#8217;ha d&#8217;executar: aquesta tasca la fa el <a href="http://ca.wikipedia.org/wiki/Planificador">planificador</a> (<em><a href="http://en.wikipedia.org/wiki/Scheduling_(computing)">scheduler</a></em>). Realment, però, aquest es divideix en varis components:</p>
<ul>
<li><strong><em><span style="font-style: normal;">Planificador a llarg termini</span><span style="font-weight: normal; font-style: normal;"> (</span><a href="http://de.wikipedia.org/wiki/Long-term-scheduling"><span style="font-weight: normal;">Long-term scheduler</span></a></em></strong> / Job Scheduler): gestiona la cua de «<em>ready</em>» (llista de processos residents en la memòria principal i a punt per executar-se).</li>
<li><strong>Planificador a curt termini</strong> (<em>Short-term scheduler</em> / <em>CPU Scheduler</em>): selecciona els processos / fils que s&#8217;executen en cada moment.</li>
</ul>
<p>El planificador a curt termini es pot executar de forma «preemptiva<em>»</em> (<em>preemptive</em>), si el nucli obliga a parar al fil, o «no preemptiva» si és el fil qui abandona la CPU (perquè fa una crida bloquejant -una operació d&#8217;entrada/sortida, una espera, etc.- o acaba). Quan el canvi és «preemptiu» hi ha un canvi d&#8217;estat de «<em>running</em>» a «<em>ready</em>».</p>
<p><strong>Polítiques de planificació</strong></p>
<p>Algunes estratègies segons les quals es pot dur a terme la planificació:</p>
<ul>
<li><strong><em>First-Come, First-Served</em><span style="font-weight: normal;"> (FCFS o FIFO)</span></strong><br />
És la més senzilla de totes: s&#8217;executa el primer programa que estigui a punt, fins que aquest torni a cedir el control al sistema operatiu. Veiem que es tracta d&#8217;una política no «preemptiva».</li>
<li><strong><em>Round Robin</em></strong> (RR)<br />
Cada procès té la CPU durant un temps prefixat (<em>quantum</em>) o fins que es bloqueja (per ex., inicia una operació d&#8217;entrada/sortida o una espera).</li>
</ul>
<p>En la pràctica s&#8217;acostuma a utilitzar un model híbrid de varies estratègies i pot ser que s&#8217;utilitzin les estadístiques proporcionades pel sistema de comptabilitat (<em>accounting</em>).</p>
<p>A més, molts sistemes permeten que l&#8217;administrador estableixi prioriats diferents a certs processos. En aquest cas, però, cal evitar problemes com el de <strong><em><a href="http://en.wikipedia.org/wiki/Resource_starvation">starvation</a></em><span style="font-weight: normal;"> (que un procés tingui tan baixa prioritat que no arribi a executar-se mai).</span></strong></p>
<p><strong>El planificador a mig termini</strong> (<em>medium-term scheduler</em>)</p>
<p>Quan s&#8217;executen moltes aplicacions concurrents (o bé, algunes aplicacions especialment pesades), pot ser que no càpiguen totes les instruccions i dades dels programes en la memòria RAM. Quan aquest és el cas, molts sistemes operatius moderns són capaços de moure part de la memòria que no s&#8217;estigui utilitzant al disc dur (operació que es coneix com a <em><a href="http://en.wikipedia.org/wiki/Paging"><strong>swap out</strong></a></em>; la destinació al disc pot ser tant un fitxer especial -Windows- com una <a href="https://help.ubuntu.com/community/SwapFaq">partició d&#8217;intercanvi</a> -UNIX-) per a fer lloc per a més dades. Quan les dades mogudes tornen a ser necessàries (perquè és el torn d&#8217;executar-se d&#8217;un programa que les necessita), aquestes es tornen a copiar a la memòria, movent algunes altres dades al disc si és necessari.</p>
<p>Si hi ha massa processos actius, pot arribar-se a una situació de <em><a href="http://en.wikipedia.org/wiki/Thrashing_(computer_science)">sobrepaginació</a></em>, on el sistema estigui més temps intercanviant dades de programa entre la memòria i el disc que executant els programes en sí. Per evitar això, s&#8217;introdueix el <strong>planificador a mig termini</strong>, el qual s&#8217;encarrega de controlar la quantitat de processos que s&#8217;executen simultàniament (posant en pausa alguns processos de la cua de «<em>ready</em>»).</p>
<h4>Memòria</h4>
<p>Podem parlar d&#8217;<strong>adreces físiques</strong> (reals) i d&#8217;<strong>adreces lògiques</strong>. Un component <em>hardware</em>, la <strong><a href="http://ca.wikipedia.org/wiki/Unitats_de_gesti%C3%B3_de_mem%C3%B2ria">unitat de gestió de memòria</a></strong> (<em>Memory Management Unit</em>, MMU) s&#8217;encarrega de fer la traducció, vigilar que un programa no es surti del seu espai de memòria, etc. La memòria d&#8217;un mateix programa és pot separar en diferents seccions: <strong>codi</strong>, <strong><em>heap</em><span style="font-weight: normal;"> (no executable), </span>pila</strong> (<strong><em>stack</em><span style="font-weight: normal;">;  no executable), etc.</span></strong></p>
<p><strong>Assignació de memòria</strong></p>
<ul>
<li><strong><a href="http://ca.wikipedia.org/wiki/Paginaci%C3%B3_de_mem%C3%B2ria">Paginació</a></strong><br />
La memòria es divideix en <strong>marcs</strong> (<em>frames</em>) d&#8217;una mida preestablerta (per exemple, 4KiB), cadascun dels quals pot acollir una <strong>pàgina</strong>.<br />
La paginació presenta un problema de <strong><a href="http://en.wikipedia.org/wiki/Fragmentation_(computer)#Internal_fragmentation">fragmentació interna</a></strong>, ja que quan la quantitat de memòria requerida per un programa no és múltiple de la mida de pàgina, es desaprofitarà part d&#8217;un marc.</li>
<li><strong><a href="http://ca.wikipedia.org/wiki/Segmentaci%C3%B3_de_mem%C3%B2ria">Segmentació</a></strong><br />
Amb el sistema de segmentació la memòria es reserva un <strong>segment</strong> de memòria per a cada <strong>secció</strong> del programa (instruccions, pila, <em>heap</em>, etc). Així la memòria es divideix de forma lògica i cada segment de memòria pot tenir assignats uns permisos diferents (per exemple, si el seu contingut és executable com a instruccions o no). Per accedir a memòria segmentada s&#8217;utilitzen adreces compostes per un identificador del segment i un <em>desplaçament</em> (nombre de <em>bytes</em> -quan l&#8217;adreçament de memòria és a nivell de <em>byte</em>- a sumar a l&#8217;adreça inicial del segment).<br />
La memòria corresponent a un segment ha de ser contigua, de manera que en aquest cas tenim un problema de <a href="http://en.wikipedia.org/wiki/Fragmentation_(computer)#External_fragmentation"><strong>fragmentació externa</strong></a>: quan entre dos segments queda un espai de memòria buit, aquest no pot ser utilitzat si és més petit que les seccions dels programes.</li>
</ul>
<p>Per reduir els problemes del sistema de segmentació, a la pràctica s&#8217;acostuma a utilitzar una combinació de tots dos, la <strong>segmentació paginada</strong>, on els segments de memòria que es troben dividits en pàgines. Així la memòria té l&#8217;estructura lògica de la segmentació però amb la fragmentació interna de la paginació (la qual aprofita millor la memòria).</p>
<p><strong>Unitat de gestió de memòria</strong> (MMU)</p>
<p>Ja hem comentat breument que la MMU s&#8217;ocupa de traduir les adreces lògiques (tal com les veuen els programes) a adreces físiques. També s&#8217;encarrega d&#8217;evitar l&#8217;accés a memòria aliena al programa que s&#8217;està executant i, quan l&#8217;assignació fa ús d&#8217;un sistema de segmentació, de fer respectar altres possibles restriccions.</p>
<p>Amb aquesta finalitat, el sistema operatiu disposa d&#8217;una <strong><a href="http://en.wikipedia.org/wiki/Page_table">taula de pàgines</a></strong>. En la majoria de sistemes moderns, la MMU també disposa d&#8217;una unitat de <a href="http://ca.wikipedia.org/wiki/Mem%C3%B2ria_cau">memòria cau</a> (<em>cache</em>) anomenada <strong>TLB</strong> (<a href="http://en.wikipedia.org/wiki/Translation_lookaside_buffer">translation lookaside buffer</a>).</p>
<p>Quan un programa accedeix a memòria, es cerca la traducció de l&#8217;adreça virtual que proporcioni al TLB. Si la traducció es troba a la memòria cau (<em>TLB hit</em>), retorna l&#8217;adreça física i l&#8217;accés a memòria pot continuar. En canvi, si no hi és (<em>TLB miss</em>), es passa a cercar la traducció a la taula de pàgines. La taula de pàgines inclou, juntament a l&#8217;adreça virtual i l&#8217;adreça física, un bit de validació que indica si l&#8217;adreça física és vàlida o si el contingut cercat ha estat mogut a l&#8217;espai d&#8217;intercanvi (és una <strong>pàgina no resident</strong>); si és el darrer cas, es produeix una excepció i es notifica al sistema operatiu perquè carregui les dades i actualitzi la taula de pàgines. Un cop s&#8217;ha trobat una adreça vàlida a la taula de pàgines, aquesta es grava a la <em>TLB</em> i es repeteix l&#8217;accés a memòria.</p>
<p>En sistemes de 32 bits i amb una mida de pàgina de 4KiB, hi poden haver 2^20 pàgines (2^32 bytes / 4 KiB), el qual requereix una taula de pàgines de <abbr title="2^20 bytes / 4 bytes per adreça / 1024 / 1024. A aquest nombre falta sumar-li l'espai requerit per als bits de validació.">4MiB</abbr>. Per reduir la mida de la taula de pàgines es pot implementar una taula de pàgines <a href="http://en.wikipedia.org/wiki/Page_table#Multilevel_page_table">multi-nivell</a> (<em>directori de pàgines</em> -&gt; <em>taula de pàgines</em>).</p>
<p><strong>Memòria dinàmica (<em>heap</em>)</strong></p>
<p>Quan un programa no sap quanta memòria necessitarà en temps de compilació, pot reservar memòria de forma dinàmica en temps d&#8217;execució. En sistemes Linux, això es fa amb la crida a sistema <strong><em>brk</em></strong> (en C: <a href="http://manpages.ubuntu.com/manpages/maverick/en/man2/brk.2.html">brk i sbrk</a>).</p>
<p>La llibreria estàndard del llenguatge C ofereix un seguit de funcions de més alt nivell que s&#8217;encarreguen de gestionar aquest tipus de crides de forma més eficient (reserven espai per avançat per reduir el nombre de crides a sistema, re-aprofiten l&#8217;espai anteriorment alliberat, etc). Es tracta de les funcions <a href="http://manpages.ubuntu.com/manpages/maverick/en/man3/malloc.3.html"><em>malloc</em> i <em>free</em></a>.</p>
<h4>Bibliografia</h4>
<ul>
<li><a href="http://codex.cs.yale.edu/avi/os-book/OS8/os8c/index.html">Operating System Concepts</a>; Silberschatz, Galvin and Gagne.</li>
<li><a href="http://oreilly.com/catalog/9780596000028">Understanding the Linux Kernel</a>; Bovet and Cesati.</li>
<li><a href="http://docencia.ac.upc.edu/FIB/grau/SO/#Documentacio">Pàgina web de l&#8217;assignatura</a> (FIB)</li>
</ul>
<p><strong>Veure també&#8230;</strong></p>
<ul>
<li><a href="http://www-est.fib.upc.es/~marc.mauri/ApuntsT1SO.pdf">Apunts de Sistemes Operatius</a>, per Marc Mauri.</li>
</ul>
<hr />
<p><small>
<a href="http://bloc.eurion.net/archives/2010/apunts-de-sistemes-operatius/#comments">One comment</a><br />
© Siegfried-Angel Gevatter Pujals, 2010. |
<a href="http://bloc.eurion.net/archives/2010/apunts-de-sistemes-operatius/">Permalink</a> |
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/3.0/">License</a> |
Post tags: <a href="http://bloc.eurion.net/archives/tag/apunts/" rel="tag">apunts</a>, <a href="http://bloc.eurion.net/archives/tag/fib/" rel="tag">fib</a>, <a href="http://bloc.eurion.net/archives/tag/linux/" rel="tag">linux</a>, <a href="http://bloc.eurion.net/archives/tag/operating-systems/" rel="tag">operating systems</a>, <a href="http://bloc.eurion.net/archives/tag/sistemes-operatius/" rel="tag">sistemes operatius</a><br/>
</small></p><p class="wp-flattr-button"></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2010/apunts-de-sistemes-operatius/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Debious &#8211; A dubious Debian packaging GUI</title>
		<link>http://bloc.eurion.net/archives/2010/debious-a-dubious-debian-packaging-gui/</link>
		<comments>http://bloc.eurion.net/archives/2010/debious-a-dubious-debian-packaging-gui/#comments</comments>
		<pubDate>Sat, 16 Oct 2010 12:49:50 +0000</pubDate>
		<dc:creator>RainCT</dc:creator>
				<category><![CDATA[Planet Debian]]></category>
		<category><![CDATA[Planet Ubuntu]]></category>
		<category><![CDATA[Debian]]></category>
		<category><![CDATA[packaging]]></category>
		<category><![CDATA[Ubuntu]]></category>

		<guid isPermaLink="false">http://bloc.eurion.net/?p=753</guid>
		<description><![CDATA[Just some little (unfinished) concept mockup. Seeing that much of it still ends up as a &#8220;text box with syntax highlighting&#8221; it&#8217;d probably make sense to implement it as a gedit plugin. Balsamiq source XML Related posts: Debian Games Team Meeting This announcement was provided by Martin Erik Werner. I&#8217;m reproducing... Packaging: Test-building your packages [...]]]></description>
			<content:encoded><![CDATA[<p>Just some little (unfinished) concept mockup. Seeing that much of it still ends up as a &#8220;text box with syntax highlighting&#8221; it&#8217;d probably make sense to implement it as a gedit plugin.</p>
<p style="text-align: center;"><a href="http://bloc.eurion.net/wp-content/uploads/2010/10/debious.png"></a><a href="http://bloc.eurion.net/wp-content/uploads/2010/10/debious.png"><img class="size-large wp-image-754 aligncenter" title="Debious - A dubious Debian packaging GUI" src="http://bloc.eurion.net/wp-content/uploads/2010/10/debious-1024x523.png" alt="" width="1024" height="523" /></a><a href="http://bloc.eurion.net/wp-content/uploads/2010/10/debious_balsamiq.txt">Balsamiq source XML</a></p>
<p>Related posts:<ol>
<li><a href='http://bloc.eurion.net/archives/2011/debian-games-team-meeting/' rel='bookmark' title='Debian Games Team Meeting'>Debian Games Team Meeting</a> <small>This announcement was provided by Martin Erik Werner. I&#8217;m reproducing...</small></li>
<li><a href='http://bloc.eurion.net/archives/2009/test-build-debian-packages/' rel='bookmark' title='Packaging: Test-building your packages'>Packaging: Test-building your packages</a> <small>Short version: how to test-build Debian/Ubuntu packages in a chroot...</small></li>
<li><a href='http://bloc.eurion.net/archives/2009/one-week-with-debian/' rel='bookmark' title='One week with Debian'>One week with Debian</a> <small>Jaunty was a great experience, until around a month (or...</small></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://bloc.eurion.net/archives/2010/debious-a-dubious-debian-packaging-gui/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

