Problem:
Score : 600 points

Problem Statement

A bracket sequence is a string that is one of the following:

An empty string;

The concatenation of (, A, and ) in this order, for some bracket sequence A ;

The concatenation of A and B in this order, for some non-empty bracket sequences A and B /

Given are N strings S_i. Can a bracket sequence be formed by concatenating all the N strings in some order?

Constraints

1 \leq N \leq 10^6

The total length of the strings S_i is at most 10^6.

S_i is a non-empty string consisting of ( and ).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If a bracket sequence can be formed by concatenating all the N strings in some order, print Yes; otherwise, print No.

Sample Input 1

2
)
(()

Sample Output 1

Yes

Concatenating (() and ) in this order forms a bracket sequence.

Sample Input 2

2
)(
()

Sample Output 2

No

Sample Input 3

4
((()))
((((((
))))))
()()()

Sample Output 3

Yes

Sample Input 4

3
(((
)
)

Sample Output 4

No

Solution in Perl (5.26.1) (judge verdict: Wrong Answer)

#!/usr/bin/perl
use Data::Dumper;
use sort 'stable';          # guarantee stability

my ($n) = map { $_ - 0 } split(/\s+/,<STDIN>);

my @d = ();

my $tot_lv = 0;

for(my $i=0;$i<$n;$i++){
  my $s = scalar(<STDIN>);
  $s =~ s/[\x00-\x20]+$//ios;
  my $dps = 0;
  my $x = 0;
  for(my $j=0;$j<length($s);$j++){
    if( substr($s,$j,1) eq '(' ){
      $x ++;
    } else {
      $x --;
      $dps = $x if $x < $dps;
    }
  }
  push(@d,+[$i,$x,$dps, ( substr($s,0,1) eq '(' ? 1 : undef ) , ( substr($s,0,1) eq ')' ? 1 : undef ) ]);
  $tot_lv += $x;
}

if( $tot_lv != 0 ){
  print "No\n";  exit(0);
}

# dps>=0 かつ、最初可能
my @d2 = grep { $_->[2] >= 0 and $_->[3]==1 } @d;
if( $#d2<0 ){
  print "No\n";  exit(0);
}
# dps==end かつ、最後可能
my @d3 = grep { $_->[1] == $_->[2] and $_->[4] == 1 } @d;
if( $#d3<0 ){
  print "No\n";  exit(0);
}

#d2,d3が両方選べるか？
if( $#d2 == 0 and $#d3 == 0 and $d2[0]->[0] == $d3[0]->[0] ){
  print "No\n";  exit(0);
}

my $fst = -1; my $f_v = +[];
my $lst = -1; my $l_v = +[];

if( $#d2 == 0 ){
  $fst = $d2[0]->[0];
  $f_v = $d2[0];
} elsif( $#d3 == 0 ){
  $lst = $d3[0]->[0];
  $l_v = $d3[0];
}

if( $fst<0 ){
  my @d2t = grep { $_->[0] != $lst } @d2;
  $fst = $d2t[0]->[0];
  $f_v = $d2t[0];
}
if( $lst<0 ){
  my @d3t = grep { $_->[0] != $fst } @d3;
  $lst = $d3t[0]->[0];
  $l_v = $d3t[0];
}

# 最初と最後を決めたら d

my @d4 = sort { &f($b->[2]) <=> &f($a->[2]) } sort { $b->[1] <=> $a->[1] } grep { $_->[0] != $lst and $_->[0] != $fst } @d;

my $res = 'Yes';
my $x = $f_v->[1];

for(my $i=0;$i<$n-2;$i++){
  if( $x + $d4[$i]->[2] < 0 ){
    $res = 'No';
    last;
  }
  $x += $d4[$i]->[1];
}

print "$res\n";

sub f {
  my $x = shift;
  $x = -10**6 - 10 - $x if( $x < 0 );
  return $x;
}