2822 爱在心中
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 钻石 Diamond
题目描述 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
第一问就是SCC个数。。
第二问进行缩点,只是用sccno[]来缩,统计出度为0的强连通分量,因为如果这个SCC被其他SCC说爱,且这个SCC可以连接下一个SCC那么他们必然构成一个更大的SCC,矛盾,因此统计出度。。。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<iomanip>
#include<ctime>
#include<climits>
#include<cctype>
#include<algorithm>
#ifdef WIN32
#define AUTO "%I64d"
#else
#define AUTO "%lld"
#endif
using namespace std;
const int maxn=50005;
const int INF=0x3f3f3f3f;
struct Edge
{
int to,next;
}edge[maxn];
int head[maxn];
int maxedge;
inline void addedge(int u,int v)
{
edge[++maxedge]=(Edge){v,head[u]};
head[u]=maxedge;
}
int n,m;
void init()
{
scanf("%d%d",&n,&m);
memset(head,-1,sizeof(head));
for(int i=1;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
addedge(x,y);
}
}
struct SCC
{
int cnt;
vector <int> scc[maxn];
void clear()
{
cnt=0;
for(int i=1;i<=n+1;i++) scc[i].clear();
}
void add(int x) { scc[cnt].push_back(x); }
}Scc;
int dfs_clock,dfn[maxn],bccno[maxn];
bool insta[maxn];
stack <int> sta;
int dfs(int u)
{
int lowu=dfn[u]=++dfs_clock;
sta.push(u);insta[u]=true;
for(int i=head[u];~i;i=edge[i].next)
{
int v=edge[i].to;
if(!dfn[v])
{
int lowv=dfs(v);
lowu=min(lowu,lowv);
}
else if(insta[v]) lowu=min(lowu,dfn[v]);
}
if(lowu>=dfn[u])
{
Scc.cnt++;
int tmp;
do
{
tmp=sta.top();sta.pop();insta[tmp]=false;
Scc.add(tmp);bccno[tmp]=Scc.cnt;
}while(tmp^u);
}
return lowu;//never forgets!!!
}
priority_queue <int,vector<int>,greater<int> > Ans;
int out[maxn];
void work()
{
for(int i=1;i<=n;i++)
if(!dfn[i]) dfs(i);
int ans=Scc.cnt;
for(int i=1;i<=Scc.cnt;i++)
if(!(Scc.scc[i].size()^1)) ans--;
printf("%d\n",ans);
if(!ans) { printf("-1\n"); return; }
for(int i=1;i<=n;i++)
for(int j=head[i];~j;j=edge[j].next)
if(bccno[i]^bccno[edge[j].to]) out[bccno[i]]++;
bool legal=false;
int scc_pos,scc_cnt;
for(int k=1;k<=Scc.cnt;k++)
{
if(Scc.scc[k].size()==1 || out[k]^0) continue;
if(legal) { legal=false;break; }
else legal=true,scc_pos=k,scc_cnt=Scc.scc[k].size();
}
if(legal)
{
for(int i=0;i<scc_cnt;i++)
Ans.push(Scc.scc[scc_pos][i]);
for(int i=1;i<scc_cnt;i++)
printf("%d ",Ans.top()),Ans.pop();
printf("%d\n",Ans.top()),Ans.pop();
}
else printf("-1\n");
}
int main()
{
#ifdef Local
freopen("love.in","r",stdin);
freopen("love.out","w",stdout);
#endif
init();
work();
return 0;
}