经典题目,注意字符串长度要离散化,否则就会有
O(L2)
的复杂度加成。。。
用map就行了,然后男连女,求强连通判断就行了。
然后就是Tarjan裸题。
#include<map>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100005;
template<class T>inline void read(T &res){
static char ch;T flag=1;
while((ch=getchar())<'0'||ch>'9')if(ch=='-')flag=-1;res=ch-48;
while((ch=getchar())>='0'&&ch<='9')res=res*10+ch-48;res*=flag;
}
string str;
map<string,int> mp;
struct data{
int to,nxt;
}E[N];
int n,m,sccon[N],scc,tot,cnt,ins[N],ans,st[N],top,head[N],dfn[N],vis[N],low[N];
void tarjan(int u){
vis[u]=ins[u]=1;st[++top]=u;
low[u]=dfn[u]=++cnt;
for(register int v,i=head[u];i;i=E[i].nxt){
if(v=E[i].to,!vis[v])tarjan(v),low[u]=min(low[u],low[v]);
else if(ins[v])low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u]){
++scc;int v;
do v=st[top--],sccon[v]=scc,ins[v]=0;
while(v!=u);
}
}
void addedge(int x,int y){
E[++tot].nxt=head[x],head[x]=tot,E[tot].to=y;
}
int main(){
read(n);
for(register int i=1;i<=n;i++)
cin>>str,mp[str]=i,cin>>str,mp[str]=i+n,addedge(i,i+n);
read(m);
for(register int x,y,i=1;i<=m;i++)
cin>>str,x=mp[str],cin>>str,y=mp[str],addedge(y,x);
for(register int i=1;i<=n;i++)
if(!vis[i])tarjan(i);
for(register int i=1;i<=n;++i){
if(sccon[i]==sccon[i+n])printf("Unsafe\n");
else printf("Safe\n");
}
return 0;
}