P1407 [国家集训队] 稳定婚姻
题解
二分图,分为两类,一类是指向,一类是被指向
在这里,只需要建立情人之间的边就行,因为找情人能否成功
code
#include<bits/stdc++.h>
#define ll long long
using namespace std;
vector<int> G[10000];
int match[10000]={0};
bool vis[10000]={0};
bool dfs(int now)//找情人
{
    for(auto next:G[now])
    {
        if(vis[next]) continue;
        vis[next]=1;
        if(match[next]==0||dfs(match[next])) return 1;
    }
    return 0;
}
void solve()
{
    int n;
    cin>>n;
    map<string,int> mp;
    int cnt=0;
    for(int i=1;i<=n;i++)
    {
        string s1,s2;
        cin>>s1>>s2;
        int x,y;
        if(!mp[s1]) mp[s1]=++cnt;
        x=mp[s1];
        if(!mp[s2]) mp[s2]=++cnt;
        y=mp[s2];
        match[y]=x;
    }
    int m;
    cin>>m;
    for(int i=1;i<=m;i++)
    {
        string s1,s2;
        cin>>s1>>s2;
        int x=mp[s1],y=mp[s2];
        G[x].push_back(y);
        G[y].push_back(x);
    }
    for(int i=1;i<=cnt;i+=2)
    {
        memset(vis,0,sizeof vis);
        match[i+1]=0;
        if(dfs(i)) cout<<"Unsafe\n";
        else cout<<"Safe\n";
        match[i+1]=i;
    }
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t=1;
    //cin>>t;
    while(t--) solve();
    return 0;
}
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号