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 ithmatrix with the jth matrix.
Dr. Wail can multiply the ith matrix with the jthmatrix, if the number of columns in the ithmatrix is equal to the number of rows in the jthmatrix.
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 ithmatrix.
Output
For each test case, print a single line containing how many pairs of indices i and jexist, such that Dr. Wail can multiply the ithmatrix 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.
题意:在n个矩阵中找出满足矩阵乘法的pair个数。
题解:map映射简单应用,我们先将行数分别放入map集合,之后在map中一一找出列指标的出现次数,加起来即可。
注意输入输出。
反思:map知识掌握不牢固,打比赛时不知如何下手。学习map!!!
#include<iostream>
#include<queue>
#include<map>
#include<stdio.h>
#define mem(a,x) memset(a,x,sizeof(a));
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long ll;
typedef pair<int, int>P;
map<int, int>mp;
int n, m, x, y, ans;
ll sum;
string s;
const int maxn = 100010;
ll r[maxn], c[maxn];
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
mp.clear();
sum = 0;
for (int i = 1; i <= n; i++)
{
scanf("%d%d", &r[i],&c[i]);
mp[r[i]]++;
}
for (int i = 1; i <= n; i++)
sum += mp[c[i]];
cout << sum << endl;
getchar();
}
getchar();
return 0;
}