您的位置:首页 > 其它

BZOJ2140 稳定婚姻 [Tarjan]

2017-09-20 09:58 337 查看
经典题目,注意字符串长度要离散化,否则就会有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
;
int n,m,sccon
,scc,tot,cnt,ins
,ans,st
,top,head
,dfn
,vis
,low
;
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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: