Description
John usually likes to listen to music, so he bought a lot of CDs for collection, but because he usually doesn't arrange them properly, he forgets who the singers of these CDs are. Now he wants to know how many singers' albums he has collected, so he thought of a way to take out two CDs and listen to them at the same time, so that he can tell whether they are sung by the same singer. (If there is no explanation, it is considered that it is not distinguished, it is a different singer) Now he has listed a table to record which albums are the same singer, but he does not know how to deal with this pile of records, please tell him how many records he has singer's album.
Input
The first line n, m. n represents the number of CDs (marked from 1 to n respectively), and m represents the total number of groups identified by John. Each of the next m lines has two numbers a, b. Indicates that record a and record b are the same singer. (1<=n, m<=10000)
Output
The total number of singers.
Sample Input
10 9
1 2
3 4
5 2
4 6
2 6
8 7
9 7
1 6
2 4
Sample Output
3
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int n, m, x, y;
int f[10005];
int find(int v)
{
return f[v] == v ? v : f[v] = find(f[v]);
}
int merg(int v, int u)
{
int t1, t2;
t1 = find(v);
t2 = find(u);
f[t2] = t1;
return 0;
}
int main()
{
freopen("cd.in", "r", stdin);
freopen("cd.out", "w", stdout);
scanf("%d%d", &n, &m);
int sum = 0;
memset(f, 0, sizeof(f));
for (int i = 1; i <= n; i++)
f[i] = i;
for (int i = 1; i <= m; i++)
{
scanf("%d%d", &x, &y);
merg(x, y);
}
for (int i = 1; i <= n; i++)
if (f[i] == i)
sum++;
printf("%d\n", sum);
return 0;
}
The basic knowledge of map is popularized :
C++ Maps are associative containers that contain key / value pairs
begin() returns an iterator pointing to the head of the map
clear( ) removes all elements
count() returns the number of occurrences of the specified element
empty() returns true if the map is empty
end() returns an iterator pointing to the end of the map
erase() deletes an element pointed to by an iterator
find() finds an element
insert() inserts elements
size() returns the number of elements in the map
swap() exchanges two maps
upper_bound() returns the key > the first position of the given element