-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
042e64c
commit 9d5703f
Showing
5 changed files
with
27 additions
and
7 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
25 changes: 25 additions & 0 deletions
25
progettazione di algoritmi/esercizi/sottoalbero da vettore dei padri.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
Dato un albero di $n$ nodi rappresentato tramite il vettore dei padri $P$ e un nodo $x$, progettare un algoritmo che in tempo $O(n)$ produce la lista dei nodi presenti nel sottoalbero radicato in $x$. | ||
|
||
```python | ||
def salbero(P): | ||
n = len(P) | ||
alb = [[] for _ in range(n)] | ||
|
||
for i in range(n): | ||
if P[i] != i: alb[P[i]].append(i) | ||
|
||
return alb | ||
|
||
def DFS(G, x, sottoalbero): | ||
sottoalbero.append(x) | ||
for i in G[x]: | ||
DFS(G, i, sottoalbero) | ||
|
||
return sottoalbero | ||
|
||
G = salbero(P) | ||
sottoalbero = DFS(G, x, []) | ||
``` | ||
|
||
- salbero è $O(n)$ | ||
- $G$ è un albero, quindi $O(n+m)=O(n)$ per la DFS |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters