Tutorial
Tutorial is loading...
Solution O(nm) (C++)
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100;
void solve()
{
int n, m, i, j;
cin >> n >> m;
int a[MAX_N + 5], b[MAX_N + 5];
int ans = 0;
for (i = 0; i < n; i++)
cin >> a[i];
for (i = 0; i < m; i++)
cin >> b[i];
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
if (a[i] == b[j])
ans++;
cout << ans << '\n';
}
int main()
{
int t;
cin >> t;
while (t--)
solve();
}
Solution O(nm) (Java)
import java.util.Scanner;
public class Main {
static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0)
solve();
sc.close();
}
public static void solve() {
int n, m, i, j;
n = sc.nextInt();
m = sc.nextInt();
int[] a = new int[n];
int[] b = new int[m];
int ans = 0;
for (i = 0; i < n; i++)
a[i] = sc.nextInt();
for (i = 0; i < m; i++)
b[i] = sc.nextInt();
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
if (a[i] == b[j])
ans++;
System.out.println(ans);
}
}
Solution O(nm) (Python)
def solve():
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = 0
for x in a:
ans += x in b
print(ans)
t = int(input())
for _ in range(t):
solve()
Solution O(nmlogn) (C++)
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int n, m, i;
cin >> n >> m;
set<int> s;
int ans = 0;
for (i = 0; i < n; i++)
{
int x;
cin >> x;
s.insert(x);
}
for (i = 0; i < m; i++)
{
int x;
cin >> x;
if (s.find(x) != s.end())
ans++;
}
cout << ans << '\n';
}
int main()
{
int t;
cin >> t;
while (t--)
solve();
}
Solution O(n+m) (C++)
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100;
const int MAX_COORD = 100;
void solve()
{
int n, m, i, j;
cin >> n >> m;
bool v[MAX_COORD + 5] = { 0 };
int ans = 0;
for (i = 0; i < n; i++)
{
int x;
cin >> x;
v[x] = true;
}
for (i = 0; i < m; i++)
{
int x;
cin >> x;
if (v[x])
ans++;
}
cout << ans << '\n';
}
int main()
{
int t;
cin >> t;
while (t--)
solve();
}