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 is friend of B and B is friend of C, then A is also friend of C. A friend circle is a group of students who are directly or indirectly friends.

You are given a N×Nmatrix 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 
1N300 
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 0i<N 
M[i][j] = M[j][i], where 0i<j<N

这个是我直接从Hackerrank上找到的Juniper Hackathon上的原题,不过我没有权限提交这道题,只好凑合写一写,用给定的输入试一试。。。好在这道题不算很难,用Coursera上Princeton Algorithm 1,week 1讲到的Union Find就能做出来,我用的就是最原始的Quick Find,时间复杂度上未必很好,准备要是无法通过test case再改进,现在就是凑合写一下,代码如下:

#include 
#include 

using namespace std;

bool isConnected(vector, int, int);
void Union(vector&, int, int);
int cnt;

int main(int argc, char** argv) {
	int N;
	cin >> N;
	cnt = N;
	vector> matrix(N, vector(N));
	for (int i = 0; i < N; ++i) {
		for (int j = 0; j < N; ++j) {
			cin >> matrix[i][j];
		}
	}

	vector 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 id, int p, int q) {
	return id[p] == id[q];
}

void Union(vector& 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;
		}
	}
}



你可能感兴趣的:(北美面试专题)