ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Composite Folder Sizes

Compute the total size of every folder in a tree where folders contain files and other folders.

สิ่งที่คุณจะได้เรียนรู้

  • Treat single items and groups the same way
  • Add child totals into their parent
  • Walk a tree from the leaves up

โจทย์

ดูฉบับแปล

The composite pattern treats single objects and groups of objects the same way. A folder's size is its own files plus the sizes of everything inside it, however deep.

There are n items numbered 0 to n − 1 forming a tree. parents[i] is the folder that contains item i, or -1 for the root (exactly one item). sizes[i] is the size of item i's own content.

Implement composite_folder_sizes(parents, sizes).

Input

parents: The parent of each item.

sizes: The own size of each item.

Output

Return, for every item, its total size: its own size plus the totals of all its children.

เงื่อนไข

1 ≤ n ≤ 100,000

0 ≤ sizes[i] ≤ 10^9; parents describe a single tree

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
sizes = [1, 2, 3, 4]
parents = [-1, 0, 0, 1]

ผลลัพธ์ที่คาดหวัง:
expected = [10, 6, 3, 4]
อินพุต:
std::vector<long long> sizes = {1, 2, 3, 4};
std::vector<long long> parents = {-1, 0, 0, 1};

ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {10, 6, 3, 4};
อินพุต:
long[] sizes = new long[] {1, 2, 3, 4};
long[] parents = new long[] {-1, 0, 0, 1};

ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {10, 6, 3, 4};

คำอธิบาย

Item 3 (size 4) is inside item 1, so item 1 totals 2 + 4 = 6. The root holds items 1 and 2: 1 + 6 + 3 = 10. Result: [10, 6, 3, 4].

ตัวอย่างที่ 2
อินพุต:
sizes = [5, 0, 7]
parents = [1, -1, 1]

ผลลัพธ์ที่คาดหวัง:
expected = [5, 12, 7]
อินพุต:
std::vector<long long> sizes = {5, 0, 7};
std::vector<long long> parents = {1, -1, 1};

ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {5, 12, 7};
อินพุต:
long[] sizes = new long[] {5, 0, 7};
long[] parents = new long[] {1, -1, 1};

ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {5, 12, 7};

คำอธิบาย

The root is item 1 with no content of its own; it contains items 0 and 2: 0 + 5 + 7 = 12.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

A folder's total is its own size plus its children's totals.

คำใบ้ 2

Process children before parents, for example in reverse depth order.

คำใบ้ 3

Avoid deep recursion on long chains; an explicit stack or ordering is safer.

ความซับซ้อนที่คาดหวัง

O(n) time, O(n) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก