1. 程式人生 > >codves 2822 愛在心中

codves 2822 愛在心中

icon isp stack i++ style st2 truct == include

            2822 愛在心中 時間限制: 1 s 空間限制: 128000 KB 題目描述 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

解:強聯通分量;

技術分享
#include<cstdio>
#include<cstring>
#include<algorithm>
using std::min;
const int N=100010; 
struct node
{
    int next,to,from;
}e[N],e2[N];
int first[N],first2[N];
int book[N];
int dfn[N],low[N],stack[N],cd[N];
int
cnt=0; void insert(int v,int u) { e[++cnt].to=u;e[cnt].from=v;e[cnt].next=first[v];first[v]=cnt; } int tot=0,top=0,num=0; int size[N],color[N]; void tarjan(int x) { dfn[x]=low[x]=++tot; book[x]=1;stack[++top]=x; for(int i=first[x];i;i=e[i].next) { if(!dfn[e[i].to]) tarjan(e[i].to),low[x]=min(low[x],low[e[i].to]); else if(book[e[i].to]) low[x]=min(low[x],low[e[i].to]); } if(dfn[x]==low[x]) { ++num; while(stack[top]!=x) { book[stack[top]]=0; color[stack[top]]=num; size[num]++; top--; } book[x]=0; color[x]=num; size[num]++; top--; } } void insert2(int v,int u) { e2[++cnt].to=u;e2[cnt].next=first2[v];first2[v]=cnt; } int main() { int n,m; scanf("%d %d",&n,&m); int v,u; for(int i=1;i<=m;i++) { scanf("%d %d",&v,&u); insert(v,u); } int ans=0; for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i); for(int i=1;i<=num;i++) if(size[i]!=1) ans++; printf("%d\n",ans); cnt=0; for(int i=1;i<=m;i++) if(color[e[i].from]!=color[e[i].to]) cd[color[e[i].from]]++,insert(color[e[i].from],color[e[i].to]); ans=0; int aim=0; // printf("=======\n"); // for(int i=1;i<=num;i++) // { // printf("std:: %d , %d ",i,cd[i]); // for(int j=1;j<=n;j++) if(color[j]==i) printf("%d ",j); // printf("\n"); // } for(int i=1;i<=num;i++) if(!cd[i]) ans++,aim=i; if(ans!=1) printf("-1"); else { if(size[aim]==1) printf("-1"); else for(int i=1;i<=n;i++) if(color[i]==aim) printf("%d ",i); } return 0; }
codves 2822

--------------

codves 2822 愛在心中