Problem Description
DYJ分析了一下所有营员的地域关系,发现有些营员是一个城市的,其实他们只需要一张就可以了,因为一个人拿到光盘后,其他人可以带着U盘之类的东西去拷贝啊!
他们愿意某一些人到他那儿拷贝资料,当然也可能不愿意让另外一些人到他那儿拷贝资料,这与我们宣扬的团队合作精神格格不入!
现在假设总共有N个营员(2<=N<=200),每个营员的编号为1-N。DYJ给每个人发了一张调查表,让每个营员填上自己愿意让哪些人到他那儿拷贝资料。当然,如果A愿意把资料拷贝给B,而B又愿意把资料拷贝给C,则一旦A获得了资料,则B、C都会获得资料。
现在,请你编写一个程序,根据回收上来的调查表,帮助DYJ计算出组委会至少要刻录多少张光盘,才能保证所有营员回去后都能得到夏令营资料?
Input
Output
Sample Input
5 2 4 3 0 4 5 0 0 0 1 0
Sample Output
1
#include<iostream>
#include<list>
#include<queue>
using namespace std;
class Graph {
private:
list<int>*adj;
int n;
int*visited;
public:
Graph(int n) {
this->n = n;
adj = new list<int>[n+1];
visited = new int[n+1];
for (int i = 0; i <= n; i++) {
visited[i] = 0;
}
}
void setadj(int v, int w) {
adj[v].push_back(w);
}
int maxv() {
int max = -1;
int v;
int temp = 0;
int maxs;
queue<int>current;
list<int>::iterator j;
int*vi = new int[n + 1];
for (int i = 1; i <=n; i++) {
if (visited[i] == 0) {
for (int m = 1; m <= n;m++){
vi[m] = 0;
}
current.push(i);
vi[i] = 1;
while (!current.empty()) {
v = current.front();
current.pop();
temp++;
for (j = adj[v].begin(); j != adj[v].end(); j++) {
if (!vi[*j]) {
vi[*j] = 1;
current.push(*j);
}
}
}
}
if (temp > max) {
max = temp;
maxs = i;
}
temp = 0;
}
return maxs;
}
void bfs(int v) {
queue<int>temp;
list<int>::iterator i;
visited[v] = 1;
temp.push(v);
while (!temp.empty()) {
v = temp.front();
temp.pop();
for (i = adj[v].begin(); i != adj[v].end(); i++) {
if (!visited[*i]) {
temp.push(*i);
visited[*i] = 1;
}
}
}
}
bool judge() {
for (int i = 1; i <= n; i++) {
if (!visited[i])
return true;
}
return false;
}
void BFS(int v) {
int cal = 0;
bfs(v);
cal++;
while (judge()) {
bfs(maxv());
cal++;
}
cout << cal;
}
};
int main() {
int n;
cin >> n;
Graph g(n);
int temp;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> temp;
if (temp == 0) {
break;
}
g.setadj(i, temp);
}
}
g.BFS(g.maxv());
}