POJ-1904:King's Quest

 

题目大意:

n个王子n个女孩,每个王子喜欢一些编号的女孩,问在确保每个王子能找到女孩的情况下每个王子各能选择哪些女孩?题目还给出了一种完美匹配的选择情况。

 

解题思路:

刚开始自己想的是二分图匹配暴力跑情况= = ,不过肯定过不了就没写。

这道题目真的是神题,把二分图匹配问题转换成了强连通分量来解,不过目前对于这两个知识点都是一知半解,所以了解的不是很清楚。在此贴出证明过程:证明过程

 

其实这个题目有一个坑点,额,在此就不说是什么了,放一组数据在代码最后。

 

 Ac代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
#include<set>
#include<cmath>
#include<vector>
#define lson rt<<1
#define rson rt<<1|1
using namespace std;
typedef long long ll;
const int maxn=4e3+5;
const int INF=1e9+7;
const ll mod=998244353;
int n,m,tot,cnt,dfn[maxn],low[maxn],belong[maxn];
vector<int> v[maxn],ans[maxn],res;
bool vis[maxn];
stack<int> s;
void tarjan(int u)
{
    dfn[u]=low[u]=++tot;
    vis[u]=1,s.push(u);
    for(int i=0;i<v[u].size();i++)
    {
        int g=v[u][i];
        if(!dfn[g])
        {
            tarjan(g);
            low[u]=min(low[u],low[g]);
        }
        else if(vis[g]) low[u]=min(low[u],dfn[g]);
    }
    if(dfn[u]==low[u])
    {
        cnt++;
        res.clear();
        while(!s.empty())
        {
            int now=s.top();
            s.pop();vis[now]=0;
            res.push_back(now);
            belong[now]=cnt;
            if(now==u) break;
        }
        for(int i=0;i<res.size();i++)   //处理出每个王子的公主
        {
            if(res[i]<=n)
            {
                for(int j=0;j<v[res[i]].size();j++)
                {
                    if(belong[v[res[i]][j]]==cnt&&v[res[i]][j]>n)
                        ans[res[i]].push_back(v[res[i]][j]);
                }
            }
        }
    }
}
void print()    //输出每个王子所对应的公主
{
    for(int i=1;i<=n;i++)
    {
        int res=0;
        sort(ans[i].begin(),ans[i].end());
        for(int j=0;j<ans[i].size();j++) if(ans[i][j]<=n) res++;
        printf("%d",ans[i].size()-res);
        for(int j=0;j<ans[i].size();j++)
        if(ans[i][j]>n) printf(" %d",ans[i][j]-n);
        printf("\n");
    }
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int m,x;
        scanf("%d",&m);
        for(int j=0;j<m;j++)    //这里注意x+n
        {
            scanf("%d",&x);
            v[i].push_back(x+n);
        }
    }
    for(int i=1;i<=n;i++)
    {
        int x;
        scanf("%d",&x);
        v[x+n].push_back(i);
    }
    for(int i=1;i<=n;i++)
        if(!dfn[i]) tarjan(i);
    print();
    //system("pause");
}
/*
input
3
2 1 2
3 1 2 3
2 2 3
1 2 3

ouput
2 1 2
3 1 2 3
2 2 3
*/

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值