1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
#include <bits/stdc++.h>
using std::vector;

void init_io() {
  std::cin.tie(nullptr);
  std::ios::sync_with_stdio(false);
}

using Counter = int64_t;
constexpr Counter INF = 1000000000000000000LL;
constexpr size_t NONE_SIZE_T = std::numeric_limits<size_t>::max();

struct Instruction {
  Counter full = 0;
  Counter best = -INF;
  bool used = false;
};

struct Program {
  vector<Instruction> instructions;
  bool first_start_only = false;

  explicit Program(std::istream &input);
};

Program::Program(std::istream &input) {
  size_t num_ops;
  input >> num_ops;
  instructions.reserve((num_ops + 1)/2);
  Instruction current_instruction;
  Counter current_val = 0;
  bool current_instruction_exists = false;
  bool seen_w = false;
  for (size_t i=0; i<num_ops; ++i) {
    char op;
    input >> op;
    switch (op) {
      case 'W': {
        if (current_instruction_exists) {
          instructions.push_back(current_instruction);
          if (!seen_w) first_start_only = true;
        }
        seen_w = true;
        current_instruction = Instruction{};
        current_val = 0;
        current_instruction_exists = false;
      }
      break;
      case 'Z': {
        current_instruction.best = std::max(current_instruction.best, current_val);
        current_instruction.full = current_val;
        current_instruction_exists = true;
      }
      break;
      case '+': {
        int x;
        input >> x;
        current_val -= x;
      }
      break;
      case '-': {
        int x;
        input >> x;
        current_val += x;
      }
      break;
      default: {
        assert(false);
      }
      break;
    }
  }
  if (current_instruction_exists) {
    instructions.push_back(current_instruction);
    if (!seen_w) first_start_only = true;
  }
}

struct EndpointProposal {
  size_t program_idx = NONE_SIZE_T;
  Counter value = -INF;
};

void insert_proposal(std::array<EndpointProposal, 2> &arr, const EndpointProposal &proposal) {
  if (proposal.value > arr[0].value) {
    arr[1] = arr[0];
    arr[0] = proposal;
  } else if (proposal.value > arr[1].value) {
    arr[1] = proposal;
  }
}

void erase_proposal(std::array<EndpointProposal, 2> &arr, size_t program_idx) {
  if (arr[1].program_idx == program_idx) {
    arr[1] = EndpointProposal{};
  } else if (arr[0].program_idx == program_idx) {
    arr[0] = arr[1];
    arr[1] = EndpointProposal{};
  }
}

class System {
public:
  explicit System(std::istream &input);
  Counter solve();
private:
  void try_individual();
  void try_greedy();
  void try_with_large(bool start_large, bool end_large);
  void find_best_proposals(std::array<EndpointProposal, 2> &start_proposals,
                           std::array<EndpointProposal, 2> &end_proposals,
                           EndpointProposal *&start,
                           EndpointProposal *&end);

  Counter best_score = -INF;
  vector<Program> programs;
  Program *large_program = nullptr;
};

System::System(std::istream &input) {
  size_t num_programs;
  input >> num_programs;
  programs.reserve(num_programs);
  for(size_t i=0; i<num_programs; ++i) {
    Program program(input);
    if (!program.instructions.empty()) {
      programs.push_back(std::move(program));
    }
  }
}

Counter System::solve() {
  if (programs.empty()) return 0;
  try_individual();
  try_greedy();
  if (large_program) {
    for (bool start_large : {false, true}) {
      for (bool end_large : {false, true}) {
        try_with_large(start_large, end_large);
      }
    }
  }
  return best_score;
}

void System::try_individual() {
  for (const Program &program : programs) {
    Counter counter = 0;
    for (const Instruction &instruction: program.instructions) {
      counter += instruction.full;
    }
    best_score = std::max(best_score, counter);
  }
}

void System::find_best_proposals(std::array<EndpointProposal, 2> &start_proposals,
                                 std::array<EndpointProposal, 2> &end_proposals,
                                 EndpointProposal *&start,
                                 EndpointProposal *&end) {
  start = &start_proposals[0];
  end = &end_proposals[0];
  if (start->program_idx!=NONE_SIZE_T &&
      end->program_idx!=NONE_SIZE_T &&
      start->program_idx == end->program_idx &&
      programs[start->program_idx].instructions.size() == 1) {
    // Can't use the same endpoint.
    if (start_proposals[1].value > end_proposals[1].value) {
      ++start;
    } else {
      ++end;
    }
  }
}

void System::try_greedy() {
  std::vector<int> used_counts(programs.size(), 0u);
  int total_used_count = 0;
  std::array<EndpointProposal, 2> start_proposals = {};
  std::array<EndpointProposal, 2> end_proposals = {};
  Counter score = 0;

  for (size_t program_idx=0; program_idx < programs.size(); ++program_idx) {
    Program &program = programs[program_idx];
    for (Instruction &instruction: program.instructions) {
      instruction.used = false;
      if (instruction.best > 0 &&
          !(program.first_start_only && &instruction == &program.instructions.front())) {
        instruction.used = true;
        score += instruction.best;
        ++used_counts[program_idx];
        ++total_used_count;
      }
    }
    {
      const Instruction &instruction = program.instructions.front();
      EndpointProposal proposal;
      proposal.program_idx = program_idx;
      if (instruction.used) {
        proposal.value = 0;
      } else {
        proposal.value = instruction.best;
      }
      insert_proposal(start_proposals, proposal);
    }
    {
      const Instruction &instruction = program.instructions.back();
      if (!(program.first_start_only && &instruction == &program.instructions.front())) {
        // can use as an endpoint
        EndpointProposal proposal;
        proposal.program_idx = program_idx;
        if (instruction.used) {
          proposal.value = instruction.full - instruction.best;
        } else {
          proposal.value = instruction.full;
        }
        insert_proposal(end_proposals, proposal);
      }
    }
  }
  EndpointProposal *start;
  EndpointProposal *end;
  find_best_proposals(start_proposals, end_proposals, start, end);
  if (start->program_idx==NONE_SIZE_T || end->program_idx==NONE_SIZE_T) {
    // Impossible.
    return;
  }
  {
    score += start->value;
    Instruction &instruction = programs[start->program_idx].instructions.front();
    if (!instruction.used) {
      instruction.used = true;
      ++used_counts[start->program_idx];
      ++total_used_count;
    }
  }
  {
    score += end->value;
    Instruction &instruction = programs[end->program_idx].instructions.back();
    if (!instruction.used) {
      instruction.used = true;
      ++used_counts[end->program_idx];
      ++total_used_count;
    }
  }

  for (size_t program_idx = 0; program_idx < programs.size(); ++program_idx) {
    const int other_middle =
      total_used_count
      - used_counts[program_idx]
      - (start->program_idx != program_idx)
      - (end->program_idx != program_idx);

    if (used_counts[program_idx] - 1 > other_middle) {
      // Not enough other middle to fill the gaps.
      large_program = &programs[program_idx];
      return;
    }
  }

  best_score = std::max(best_score, score);
}

struct LargeDecrementEntry {
  Counter value = -INF;
  size_t prev = NONE_SIZE_T;
  size_t next = NONE_SIZE_T;
};

struct LargeDecrementEntryQueueElem {
  size_t idx = NONE_SIZE_T;
  Counter value = -INF;
};

inline bool operator<(const LargeDecrementEntryQueueElem &a,
                      const LargeDecrementEntryQueueElem &b)
{
  return a.value < b.value;
}

struct AddInstructionQueueElem {
  size_t program_idx = NONE_SIZE_T;
  size_t instruction_idx = NONE_SIZE_T;
  Counter value = -INF;
};

inline bool operator<(const AddInstructionQueueElem &a, const AddInstructionQueueElem &b) {
  return a.value < b.value;
}

void System::try_with_large(const bool start_large, const bool end_large) {
  if (start_large && end_large && large_program->instructions.size() == 1) return;
  if (!start_large && large_program->instructions.size() == 1 && large_program->first_start_only) return;

  int large_used_count = 0;
  int other_used_count = 0;
  Counter score = 0;

  // Process large program and initialize large decrement priority queue.

  Counter gap = -INF;
  vector<LargeDecrementEntry> large_decrement_entries;
  large_decrement_entries.reserve(large_program->instructions.size());

  for (Instruction &instruction : large_program->instructions) {
    instruction.used = false;
    bool erasing_forbidden = false;
    Counter instruction_score = 0;
    if (start_large && &instruction == &large_program->instructions.front()) {
      instruction.used = true;
      erasing_forbidden = true;
      instruction_score = instruction.best;
    } else if (end_large && &instruction == &large_program->instructions.back()) {
      instruction.used = true;
      erasing_forbidden = true;
      instruction_score = instruction.full;
    } else if (&instruction == &large_program->instructions.front() && large_program->first_start_only) {
      // don't use
    } else if (instruction.best > 0) {
      instruction.used = true;
      instruction_score = instruction.best;
    }

    if (instruction.used) {
      ++large_used_count;
      score += instruction_score;
      if (!large_decrement_entries.empty()) {
        LargeDecrementEntry entry;
        entry.value = gap;
        entry.prev = large_decrement_entries.size() - 1;
        large_decrement_entries.back().next = large_decrement_entries.size();
        large_decrement_entries.push_back(entry);
      }
      {
        LargeDecrementEntry entry;
        entry.value = erasing_forbidden ? -INF : -instruction_score;
        if (!large_decrement_entries.empty()) {
          entry.prev = large_decrement_entries.size() - 1;
          large_decrement_entries.back().next = large_decrement_entries.size();
        }
        large_decrement_entries.push_back(entry);
      }
      gap = instruction.full - instruction_score;
    } else {
      gap += instruction.full;
    }
  }

  std::priority_queue<LargeDecrementEntryQueueElem> large_decrement_queue;
  for (size_t i=0; i<large_decrement_entries.size(); ++i) {
    LargeDecrementEntryQueueElem elem;
    elem.idx = i;
    elem.value = large_decrement_entries[i].value;
    large_decrement_queue.push(elem);
  }

  // Process other programs and initialize queues.
  
  // [at start][at end]
  std::priority_queue<AddInstructionQueueElem> add_instruction_queue[2][2];
  std::array<EndpointProposal, 2> start_proposals = {};
  std::array<EndpointProposal, 2> end_proposals = {};

  for (size_t program_idx = 0; program_idx < programs.size(); ++program_idx) {
    Program &program = programs[program_idx];
    if (&program == large_program) continue;

    for (size_t instruction_idx=0; instruction_idx < program.instructions.size(); ++instruction_idx) {
      Instruction &instruction = program.instructions[instruction_idx];
      instruction.used = false;

      const bool at_start = instruction_idx == 0;
      const bool at_end = instruction_idx == program.instructions.size() - 1;

      if (program.first_start_only && at_start) {
        // never add
      } else if (instruction.best > 0) {
        instruction.used = true;
        score += instruction.best;
        ++other_used_count;
      } else {
        AddInstructionQueueElem elem;
        elem.program_idx = program_idx;
        elem.instruction_idx = instruction_idx;
        elem.value = instruction.best;
        add_instruction_queue[at_start][at_end].push(elem);
      }
    }

    if (!start_large) {
      const Instruction &instruction = program.instructions.front();
      EndpointProposal proposal;
      proposal.program_idx = program_idx;
      if (instruction.used) {
        proposal.value = 0;
      } else {
        proposal.value = instruction.best;
      }
      insert_proposal(start_proposals, proposal);
    }

    if (!end_large) {
      const Instruction &instruction = program.instructions.back();
      if (!(program.first_start_only && &instruction == &program.instructions.front())) {
        // can use as an endpoint
        EndpointProposal proposal;
        proposal.program_idx = program_idx;
        if (instruction.used) {
          proposal.value = instruction.full - instruction.best;
        } else {
          proposal.value = instruction.full;
        }
        insert_proposal(end_proposals, proposal);
      }
    }
  }

  // Repeatedly make improvements while necessary.
  for (;;) {
    EndpointProposal *start;
    EndpointProposal *end;
    find_best_proposals(start_proposals, end_proposals, start, end);
    if (!start_large && start->program_idx == NONE_SIZE_T) {
      // impossible
      return;
    }
    if (!end_large && end->program_idx == NONE_SIZE_T) {
      // impossible
      return;
    }

    int other_middle = other_used_count;
    if (!start_large && programs[start->program_idx].instructions.front().used) {
      --other_middle;
    }
    if (!end_large && programs[end->program_idx].instructions.back().used) {
      --other_middle;
    }
    if (large_used_count - 1 <= other_middle) {
      // We are OK!
      if (!start_large) score += start->value;
      if (!end_large) score += end->value;
      best_score = std::max(best_score, score);
      return;
    }

    // Pick an improvement from one of 5 priority queues.
    int best_queue = -1;
    Counter best_value = -INF/2;
    while (!large_decrement_queue.empty()) {
      const auto &qe = large_decrement_queue.top();
      const auto &entry = large_decrement_entries[qe.idx];
      if (entry.value != qe.value) {
        // lazily clean queue and repeat
        large_decrement_queue.pop();
        continue;
      }
      // Don't allow merging the whole large program.
      if (start_large && end_large &&
          entry.prev == 0 &&
          entry.next == large_decrement_entries.size() - 1)
      { 
        break;
      }
      const Counter val = large_decrement_queue.top().value;
      if (val > best_value) {
        best_queue = 4;
        best_value = val;
      }
      break;
    }

    for (int at_start=0; at_start<2; ++at_start) {
      for (int at_end=0; at_end<2; ++at_end) {
        const auto &q = add_instruction_queue[at_start][at_end];
        if (!q.empty()) {
          const auto &entry = q.top();
          Counter val = entry.value;
          // simulate update
          std::array<EndpointProposal, 2> new_start_proposals = start_proposals;
          std::array<EndpointProposal, 2> new_end_proposals = end_proposals;
          if (at_start && !start_large) {
            EndpointProposal proposal;
            proposal.program_idx = entry.program_idx;
            proposal.value = 0;
            erase_proposal(new_start_proposals, proposal.program_idx);
            insert_proposal(new_start_proposals, proposal);
          }
          if (at_end && !end_large) {
            Instruction &instruction = programs[entry.program_idx].instructions.back();
            EndpointProposal proposal;
            proposal.program_idx = entry.program_idx;
            proposal.value = instruction.full - instruction.best;
            erase_proposal(new_end_proposals, proposal.program_idx);
            insert_proposal(new_end_proposals, proposal);
          }
          EndpointProposal *new_start;
          EndpointProposal *new_end;
          find_best_proposals(new_start_proposals, new_end_proposals, new_start, new_end);
          if (!start_large) {
            val += new_start->value - start->value;
          }
          if (!end_large) {
            val += new_end->value - end->value;
          }

          if (val > best_value) {
            best_queue = 2*at_start+at_end;
            best_value = val;
          }
        }
      }
    }
    if (best_queue == -1) {
      // no more improvements
      return;
    } else if (best_queue == 4) {
      // large decrement
      const size_t idx = large_decrement_queue.top().idx;
      large_decrement_queue.pop();
      auto &entry = large_decrement_entries[idx];
      --large_used_count;
      score += entry.value;
      if (entry.prev == NONE_SIZE_T && entry.next == NONE_SIZE_T) {
        // last entry
        entry.value = -INF;
      } else if (entry.prev == NONE_SIZE_T) {
        // first entry: also erase next gap
        auto &next_entry = large_decrement_entries[entry.next];
        assert(next_entry.next != NONE_SIZE_T);
        auto &next_next_entry = large_decrement_entries[next_entry.next];
        next_next_entry.prev = NONE_SIZE_T;
        next_entry.value = -INF;
      } else if (entry.next == NONE_SIZE_T) {
        // last entry: also erase prev gap
        auto &prev_entry = large_decrement_entries[entry.prev];
        assert(prev_entry.prev != NONE_SIZE_T);
        auto &prev_prev_entry = large_decrement_entries[prev_entry.prev];
        prev_prev_entry.next = NONE_SIZE_T;
        prev_entry.value = -INF;
      } else {
        // middle entry: merge with two neighbors
        auto &prev_entry = large_decrement_entries[entry.prev];
        auto &next_entry = large_decrement_entries[entry.next];
        entry.value = prev_entry.value + next_entry.value - entry.value;
        prev_entry.value = -INF;
        next_entry.value = -INF;
        entry.prev = prev_entry.prev;
        entry.next = next_entry.next;
        if (entry.prev != NONE_SIZE_T) {
          large_decrement_entries[entry.prev].next = idx;
        }
        if (entry.next != NONE_SIZE_T) {
          large_decrement_entries[entry.next].prev = idx;
        }
        LargeDecrementEntryQueueElem new_elem;
        new_elem.idx = idx;
        new_elem.value = entry.value;
        large_decrement_queue.push(new_elem);
      }
    } else {
      // other increment
      const bool at_start = best_queue >> 1;
      const bool at_end = best_queue & 1;
      auto &q = add_instruction_queue[at_start][at_end];
      const auto entry = q.top();
      q.pop();
      Instruction &instruction = programs[entry.program_idx].instructions[entry.instruction_idx];
      assert(!instruction.used);
      instruction.used = true;
      score += instruction.best;
      ++other_used_count;
      if (at_start && !start_large) {
        EndpointProposal proposal;
        proposal.program_idx = entry.program_idx;
        proposal.value = 0;
        erase_proposal(start_proposals, proposal.program_idx);
        insert_proposal(start_proposals, proposal);
      }
      if (at_end && !end_large) {
        EndpointProposal proposal;
        proposal.program_idx = entry.program_idx;
        proposal.value = instruction.full - instruction.best;
        erase_proposal(end_proposals, proposal.program_idx);
        insert_proposal(end_proposals, proposal);
      }
    }
  }
}

int main() {
  init_io();
  int ntc;
  std::cin >> ntc;
  for (int tc=0; tc<ntc; ++tc) {
    System system(std::cin);
    Counter res = system.solve();
    std::cout << (-res) << "\n";
  }
}