using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Q239660
{
class Program
{
static void Main(string[] args)
{
string data = @"aaa bb 10 cc 11 dd 12
aaa cc 9 dd 4 bb 2
aaa cc 16 bb 9 dd 8
bbb a1 6 a2 9 a3 8
bbb a2 7 a3 4 a1 6";
string result = string.Join("\r\n", data.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(' ')).SelectMany(x => Enumerable.Range(0, 3).Select(y => new { a = x[0], b = x[y * 2 + 1], c = int.Parse(x[y * 2 + 2]) }))
.GroupBy(x => x.a)
.Select(x => new { a = x.Key, b = x.GroupBy(y => y.b).Select(y => new { b = y.Key, c = y.Sum(z => z.c) }) })
.Select(x => x.a + " " + string.Join(" ", x.b.Select(y => y.b + " " + y.c.ToString()))));
Console.WriteLine(result);
}
}
}