Saturday, June 13, 2015

UVa 1197 - The Suspects

// UVa 1197 - The Suspects

#include <iostream>
#include <map>
#include <vector>
#include <string.h>
#include <queue>
using namespace std;

#define MaxM 500
#define MaxN 30000

int main() {
	int m, n;
	while (cin >> n >> m && (m || n)) {
		// initialize data structures
		map<int, bool> group_map[MaxM];
		vector<int> group_members[MaxM];
		vector<int> member_groups[MaxN];
		bool lnk[MaxM][MaxM];
		memset(lnk, false, sizeof(lnk));
		// read all groups
		for (int i = 0; i < m; i++) {
			int k;
			for (cin >> k; k; k--) {
				// read member of this group
				int a;
				cin >> a;
				// create links to other groups
				for (int j = 0; j < member_groups[a].size(); j++) {
					lnk[i][member_groups[a][j]] = true;
					lnk[member_groups[a][j]][i] = true;
				}
				// update data structures
				group_map[i][a] = true;
				group_members[i].push_back(a);
				member_groups[a].push_back(i);
			}
		}
		// queue groups infected by student 0
		int sol;
		bool yet[MaxM];
		memset(yet, true, sizeof(yet));
		queue<int> q;
		for (int i = 0; i < m; i++)
			if (group_map[i][0]) {
				q.push(i);
				yet[i] = false;
			}
		if (!q.empty()) {
			// flood fill
			while (!q.empty()) {
				int now = q.front();
				q.pop();
				for (int i = 0; i < m; i++)
					if (lnk[now][i] && yet[i]) {
						q.push(i);
						yet[i] = false;
					}
			}
			// count members
			sol = 0;
			bool counted[MaxN];
			memset(counted, false, sizeof(counted));
			for (int i = 0; i < m; i++)
				if (!yet[i]) {
					for (int j = 0; j < group_members[i].size(); j++)
						if (!counted[group_members[i][j]]) {
							counted[group_members[i][j]] = true;
							sol++;
						}
				}
		} else
			sol = 1;
		cout << sol << endl;
	}

	return 0;
}

No comments:

Post a Comment