题目描述 Description
“每个人都拥有一个梦,即使彼此不相同,能够与你分享,无论失败成功都会感动。爱因为在心中,平凡而不平庸,世界就像迷宫,却又让我们此刻相逢Our Home。”
在爱的国度里有N个人,在他们的心中都有着一个爱的名单,上面记载着他所爱的人(不会出现自爱的情况)。爱是具有传递性的,即如果A爱B,B爱C,则A也爱C。
如果有这样一部分人,他们彼此都相爱,则他们就超越了一切的限制,用集体的爱化身成为一个爱心天使。
现在,我们想知道在这个爱的国度里会出现多少爱心天使。而且,如果某个爱心天使被其他所有人或爱心天使所爱则请输出这个爱心天使是由哪些人构成的,否则输出-1。
输入描述 Input Description
第1行,两个数N、M,代表爱的国度里有N个人,爱的关系有M条。
第2到第M+1行,每行两个数A、B,代表A爱B。
输出描述 Output Description
第1行,一个数,代表爱的国度里有多少爱心天使。
第2行,如果某个爱心天使被其他所有人和爱心天使所爱则请输出这个爱心天使是由哪些人构成的(从小到大排序),否则输出-1。
样例输入 Sample Input
样例输入1:
6 7
1 2
2 3
3 2
4 2
4 5
5 6
6 4
样例输入2:
3 3
1 2
2 1
2 3
样例输出 Sample Output
样例输出1:
2
2 3
样例输出2:
1
-1
数据范围及提示 Data Size & Hint
各个测试点1s
采用tarjan找环
第一问较简单,对于第二问,可以反向存图+bfs验证
强行无缩点 _(:з」∠)_
暴力的我都不好意思叫题解
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = 200000 + 5;
struct edge
{
int f,t;
}l[MAXN << 1],l1[MAXN << 1];
int next[MAXN],head[MAXN],tot,n,m;
int low[MAXN],dfn[MAXN],sccn[MAXN],size[MAXN],dfn_cnt,sccn_cnt,ans,flag[MAXN];
int huan[1001][1001];
bool used[MAXN];
void build(int f,int t)
{
l[++ tot] = (edge){f,t};
next[tot] = head[f];
head[f] = tot;
}
int next1[MAXN],head1[MAXN],tot1;
void init()
{
for(int i = 1;i <= n;i ++)
{
head[i] = -1;
head1[i] = -1;
}
}
void build1(int f,int t)
{
l1[++ tot1] = (edge){f,t};
next1[tot1] = head1[f];
head1[f] = tot1;
}
stack <int> s;
void dfs(int u)
{
low[u] = dfn[u] = ++ dfn_cnt;
s.push(u);
for(int i = head[u];i != -1;i = next[i])
{
int v = l[i].t;
if(!dfn[v])
{
dfs(v);
low[u] = min(low[u],low[v]);
}
else if(!sccn[v])
{
low[u] = min(low[u],dfn[v]);
}
}
if(low[u] == dfn[u])
{
++ sccn_cnt;
flag[sccn_cnt] = u;
while(!s.empty())
{
int t = s.top();
huan[sccn_cnt][++ size[sccn_cnt]] = t;
s.pop();
sccn[t] = sccn_cnt;
if(t == u)break;
}
}
}
queue <int> q;
void delet(int u,int flag)
{
if(u == flag){
if(sccn[l[head1[u]].t] == sccn[flag])head1[u] = next1[head1[u]];
for(int i = head1[u];i != -1;i = next1[i])
{
if(sccn[l1[next1[i]].t] == sccn[flag])
{
next1[i] = next1[next1[i]];
}
}
return;
}
for(int i = head1[u];i != -1;i = next1[i])
{
int v = l1[i].t;
if(v == flag)continue;
l1[i].f = flag;
next1[i] = head1[flag];
head1[flag] = i;
}
}
bool cmp(int a,int b)
{
return a <= b;
}
int main()
{
scanf("%d%d",&n,&m);
init();
int x,y;
for(int i = 1;i <= m;i ++)
{
scanf("%d%d",&x,&y);
build(x,y);
build1(y,x);
}
for(int i = 1;i <= n;i ++)
{
if(!dfn[i])dfs(i);
}
for(int i = 1;i <= sccn_cnt;i ++)
{
if(size[i] >= 2)ans ++;
}
printf("%d\n",ans);
for(int i = 1;i <= sccn_cnt;i ++)
{
if(size[i] == 1)continue;
memset(used,0,sizeof(used));
while(!q.empty())q.pop();
int tot = 1;
used[flag[i]] = 1;
q.push(flag[i]);
while(!q.empty())
{
int u = q.front();
q.pop();
for(int i = head1[u];i != -1;i = next1[i])
{
int v = l1[i].t;
if(used[v])continue;
used[v] = true;
tot ++;
q.push(v);
}
}
if(tot == n)
{
sort(huan[i] + 1,huan[i] + 1 + size[i],cmp);
for(int j = 1;j <= size[i];j ++)cout << huan[i][j] << " ";
return 0;
}
}
printf("-1");
return 0;
}