HDU1845 Jimmy’s Assignment(匈牙利算法)

题目链接

Jimmy’s Assignment

Jimmy is studying Advanced Graph Algorithms at his university. His most recent assignment is to find a maximum matching in a special kind of graph. This graph is undirected, has N vertices and each vertex has degree 3. Furthermore, the graph is 2-edge-connected (that is, at least 2 edges need to be removed in order to make the graph disconnected). A matching is a subset of the graph’s edges, such that no two edges in the subset have a common vertex. A maximum matching is a matching having the maximum cardinality.
Given a series of instances of the special graph mentioned above, find the cardinality of a maximum matching for each instance.
————————————————
Input
The first line of input contains an integer number T, representing the number of graph descriptions to follow. Each description contains on the first line an even integer number N (4<=N<=5000), representing the number of vertices. Each of the next 3*N/2 lines contains two integers A and B, separated by one blank, denoting that there is an edge between vertex A and vertex B. The vertices are numbered from 1 to N. No edge may appear twice in the input.
————————————————
Output
For each of the T graphs, in the order given in the input, print one line containing the cardinality of a maximum matching.
————————————————
Sample Input
2
4
1 2
1 3
1 4
2 3
2 4
3 4
4
1 2
1 3
1 4
2 3
2 4
3 4
Sample Output
2
2

题意

在N个顶点的无向正则图中,找出尽量多的点对,使得每对点中都有边。

思路

将点分为两组,找最大匹配数,由于是无向的,所以一条边需要添加两次。开始直接跑TL了,所以就把n个顶点分为两组进行优化(因为只要选择一点,另一组的对应点就不可以被再次选择了,所以直接用一半去寻找最大匹配数即可)。

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn=5005;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
bool ch[maxn];
vector<int> re[maxn];
int ed[maxn],m,n;
int find(int x)
{
    for(int i=0;i<re[x].size();i++)
    {
    	int v=re[x][i];
        if(!ch[v])//此点可选 
        {
            ch[v]=true;//标记为不可选 
            if(!ed[v]||find(ed[v])) 
            {
                ed[v]=x;
                return 1;
            }//若此点还未匹配或者已匹配的点还有其余选择 
        }
    }
    return 0;
} 
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    int a,b,t,sum;
    cin>>t;
    while(t--)
    {
        cin>>n;
        memset(ed,0,sizeof(ed));
        for(int i=0;i<n;i++)
        	re[i].clear();
        for(int i=0;i<3*n/2;i++)
        {
            cin>>a>>b;
            re[a].push_back(b);
            re[b].push_back(a);
        }//无向,需要两次添加 
        sum=0;
        for(int i=1;i<=n/2;i++)
        {
            memset(ch,false,sizeof(ch));
            if(find(i))
            	sum++;
        }//将n个顶点分为两组进行对应即可 
        cout<<sum<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值