HUST 1103 校赛 邻接表-拓扑排序

时间:2023-03-09 21:46:57
HUST 1103 校赛 邻接表-拓扑排序

Description

N students were invited to attend a party, every student has some friends, only if someone’s all friends attend this party, this one can attend the party(ofcourse if he/she has no friends, he/she also can attend it.), now i give the friendship between these students, you need to tell me whether all of them can attend the party.
Note that the friendship is not mature, for instance, if a is b’s friend, but b is not necessary a’s friend. 

Input

Input starts with an integer T(1 <= T <= 10), denoting the number of test case.
For each test case, first line contains an integer N(1 <= N <= 100000), denoting the number of students.
Next n lines, each lines first contains an integer K, denoting the number of friends belong to student i(indexed from 1). Then following K integers, denoting the K friends.
You can assume that the number of friendship is no more than 100000, and the relation like student A is himself’s friend will not be existed. 

Output

For each test case, if all of the students can attend the party, print Yes, otherwise print No. 

Sample Input

2
3
1 2
1 3
1 1
3
1 2
0
1 1

Sample Output

No
Yes

HINT

For the first case:

Student 1 can attend party only if student 2 attend it.

Student 2 can attend party only if student 3 attend it.
Student 3 can attend party only if student 1 attend it.
So no one can attend the party. 
题意:给定n个人, 第i个人依赖k个人,只有k个人都参加了,那么i才会参加。问是否所有人都能参加。
思路:数据量有些大,可能无法用并查集判是否有回路解。学长给出方法是用拓扑排序,最后将节点数量和n比较判断即可。
拓扑排序大致是查找出度为零的所有节点,压入队列,一个个弹出,同时将该点和临边删除。
用到了Vector邻接表,发现储存图真是好用。
但是我的代码还有点问题,vector并不需要开二维的,一维就够了。
 #include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <utility>
#define MAXX 100010
using namespace std;
const int INF = 0x3f3f3f3f;
pair<vector<int>, int> x;
vector< vector<int> >bel();
queue< vector<int> >qu;
int a[MAXX];
int cnt; int findpush(int n)
{
int flag = ;
for(int i = ; i <= n; i++)
{
if(a[i] == )
{
flag = ;
if(bel[i].size())
qu.push(bel[i]);
else
cnt--;
a[i] = INF;
}
}
return flag;
} int main()
{
int T, n, t, ed;
scanf("%d", &T);
while(T--)
{
scanf("%d",&n);
cnt = n; for(int i = ; i <= n; i++)
a[i] = , bel[i].clear();
for(int i = ; i <= n; i++)
{
scanf("%d", &t);
/* if(!t)
cnt--;*/
while(t--)
{
scanf("%d", &ed);
bel[ed].push_back(i);
a[i]++;
}
}
while(qu.empty())
{
int flag = findpush(n);
if(flag == )
{
if(cnt)
printf("No\n");
else printf("Yes\n");
break;
}
int temp = qu.size();
while(temp--)
{ for(int i = ; i < (qu.front()).size(); i++)
{
a[(qu.front())[i] ]--;
}
qu.pop();
cnt--;
}
}
}
}