P1407 [国家集训队]稳定婚姻
挺有意思的一个建图,夫妻之间男->女,前任之间女到男,然后判断强连通分量
#include <bits/stdc++.h> #define inf 2333333333333333 #define N 1000010 #define p(a) putchar(a) #define For(i,a,b) for(int i=a;i<=b;++i) //by war //2020.8.5 using namespace std; int T; int n,m,cnt,col,now,S,Max,tot; int dfn[N],low[N],c[N],ans; bool vis[N]; string x,y; map<string,int>mp; struct node{ int n; node *next; }*e[N]; stack<int>s; struct edge{ int x;int y; }a[N]; void in(int &x){ int y=1;char c=getchar();x=0; while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();} while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();} x*=y; } void o(int x){ if(x<0){p('-');x=-x;} if(x>9)o(x/10); p(x%10+'0'); } void push(int x,int y){ node *p; p=new node(); p->n=y; if(e[x]==0) e[x]=p; else{ p->next=e[x]->next; e[x]->next=p; } } void tarjan(int x,int fa){ dfn[x]=low[x]=++cnt; vis[x]=1; s.push(x); for(node *i=e[x];i;i=i->next){ if(i->n==fa) continue; if(!dfn[i->n]){ tarjan(i->n,x); low[x]=min(low[x],low[i->n]); } else if(vis[i->n]&&i->n!=fa) low[x]=min(low[x],dfn[i->n]); } if(low[x]==dfn[x]){ col++; do{ ans++; now=s.top(); c[now]=col; s.pop(); vis[now]=0; }while(x!=now); } } signed main(){ in(n); For(i,1,n){ cin>>x>>y; if(!mp[x]) mp[x]=++tot; if(!mp[y]) mp[y]=++tot; a[i].x=mp[x]; a[i].y=mp[y]; push(mp[x],mp[y]); } in(m); For(i,1,m){ cin>>x>>y; push(mp[y],mp[x]); } For(i,1,tot) if(!dfn[i]) tarjan(i,i); For(i,1,n){ if(c[a[i].x]==c[a[i].y]) puts("Unsafe"); else puts("Safe"); } return 0; }