Gym - 101502B. Linear Algebra Test


Dr. Wail is preparing for today's test in linear algebra course. The test's subject is Matrices Multiplication.

Dr. Wail has n matrices, such that the size of the ith matrix is (ai × bi), where ai is the number of rows in the ith matrix, and bi is the number of columns in the ith matrix.

Dr. Wail wants to count how many pairs of indices i and j exist, such that he can multiply the ith matrix with the jth matrix.

Dr. Wail can multiply the ith matrix with the jth matrix, if the number of columns in the ith matrix is equal to the number of rows in the jth matrix.


Input

The first line contains an integer T (1 ≤ T ≤ 100), where T is the number of test cases.

The first line of each test case contains an integer n (1 ≤ n ≤ 105), where n is the number of matrices Dr. Wail has.

Then n lines follow, each line contains two integers ai and bi (1 ≤ ai, bi ≤ 109) (ai ≠ bi), where ai is the number of rows in the ith matrix, and bi is the number of columns in the ith matrix.


Output

For each test case, print a single line containing how many pairs of indices i and j exist, such that Dr. Wail can multiply the ith matrix with the jth matrix.


Example
Input
1
5
2 3
2 3
4 2
3 5
9 4
Output
5

Note

As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

In the first test case, Dr. Wail can multiply the 1st matrix (2 × 3) with the 4th matrix (3 × 5), the 2nd matrix (2 × 3) with the 4th matrix (3 × 5), the 3rd matrix (4 × 2) with the 1st and second matrices (2 × 3), and the 5th matrix (9 × 4) with the 3rd matrix (4 × 2). So, the answer is 5.

思路

因为10^9,所以用map映射一下。细节见代码,map<typ1, typ2> typ1 = first, typ2 = second, typ2 = map[typ1];

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;

typedef long long LL;

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        map<int, LL> m1; // second 是Longlong,因为ans为Longlong
        map<int, LL> m2;
        int n;
        scanf("%d", &n);
        for(int i = 0; i < n; i++)
        {
            int x, y;
            scanf("%d%d", &x,&y);
            m1[x]++;
            m2[y]++;
        }
        map<int, LL>::iterator it;
        LL ans = 0;
        for(it = m1.begin(); it!= m1.end(); it++)
        {
            int cnt1 = it->first;
            int cnt2 = it->second;
            ans+=m2[cnt1]*cnt2;
        }
        printf("%lld\n", ans);
    }

}




猜你喜欢

转载自blog.csdn.net/qihang_qihang/article/details/79671888