read N
awk '{for(i=1;i<=NF;i++){print NR,$i}}' |
    sort -k2,2n -k1,1nr |
    cut -f1 |
    awk '{n[$1]++}$1==2{print 2,n[1]}$1==3{print 3}' |
    awk '$1==2{l+=$2}$1==3{print l}' |
    awk '{s+=$1}END{print s}'