BZOJ2140 稳定婚姻 [Tarjan]

4 篇文章 0 订阅

经典题目,注意字符串长度要离散化,否则就会有 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;
}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值