刻录光盘

Problem Description

在夏令营快要结束的时候,很多营员提出来要把整个夏令营期间的资料刻录成一张光盘给大家,以便大家回去后继续学习。组委会觉得这个主意不错!可是组委会一时没有足够的空光盘,没法保证每个人都能拿到刻录上资料的光盘,怎么办呢?
DYJ分析了一下所有营员的地域关系,发现有些营员是一个城市的,其实他们只需要一张就可以了,因为一个人拿到光盘后,其他人可以带着U盘之类的东西去拷贝啊!
他们愿意某一些人到他那儿拷贝资料,当然也可能不愿意让另外一些人到他那儿拷贝资料,这与我们宣扬的团队合作精神格格不入!
现在假设总共有N个营员(2<=N<=200),每个营员的编号为1-N。DYJ给每个人发了一张调查表,让每个营员填上自己愿意让哪些人到他那儿拷贝资料。当然,如果A愿意把资料拷贝给B,而B又愿意把资料拷贝给C,则一旦A获得了资料,则B、C都会获得资料。

现在,请你编写一个程序,根据回收上来的调查表,帮助DYJ计算出组委会至少要刻录多少张光盘,才能保证所有营员回去后都能得到夏令营资料?

Input

输入有多组数据,每组数据先是一个数字N,接下来N行,分别标识各个营员愿意把自己获得的资料拷贝给其他哪些营员,即输入数据的i+1行表示第i个营员愿意把资料拷贝给那些营员的编号,以一个0结束。如果一个营员不愿意拷贝资料给任何人,则相应的行只有1个0。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值