1. 程式人生 > >Two Sigma面試專題

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 <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;
		}
	}
}