Two Sigma面試專題
前段時間過了Two Sigma的第一輪HR面後,就一直沒有管,最近準備把Two Sigma的OA做了,不過還是提前準備下,從網上找了幾道面經,準備寫一寫,儘量能過OA面吧,如果過了,下一輪就是技術電話面試。。。以前還從未有過這樣的面試,所以想這次試一試。。
Two Sigma NO.1 Friend Circle
Problem Statement
There are N students
in a class. Some of them are friends, while some are not. Their friendship is transitive in nature, i.e., if A
You are given a N×N−matrix M which
consists of characters Y
or N
.
If M[i][j]=Y,
then ith and jth students
are friends with each other, otherwise not. You have to print the total number of friend circles in the class.
Input Format
First line of the input contains an integer N -
(size of the matrix), followed by N lines each having N characters.
Output Format
Print the maximum number of friend circles.
Constraints
1≤N≤300
Each element of matrix friends will be Y
or N
.
Number of rows and columns will be equal in the matrix.
M[i][i]=Y,
where 0≤i<N
M[i][j] = M[j][i],
where 0≤i<j<N
#include <iostream>
#include <vector>
using namespace std;
bool isConnected(vector<int>, int, int);
void Union(vector<int>&, int, int);
int cnt;
int main(int argc, char** argv) {
int N;
cin >> N;
cnt = N;
vector<vector<char>> matrix(N, vector<char>(N));
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
cin >> matrix[i][j];
}
}
vector<int> id(N);
for (int i = 0; i < N; ++i) {
id[i] = i;
}
for (int i = 0; i < N; ++i) {
for (int j = 0; j < i; ++j) {
if (matrix[i][j] == 'Y' and !isConnected(id, i, j)) {
Union(id, i, j);
}
}
}
cout << cnt << endl;
return 0;
}
bool isConnected(vector<int> id, int p, int q) {
return id[p] == id[q];
}
void Union(vector<int>& id, int p, int q) {
int pid = id[p];
int qid = id[q];
for (int i = 0; i < id.size(); ++i) {
if (id[i] == pid) {
id[i] = qid;
--cnt;
}
}
}