无向边的二分匹配

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



#include<iostream>
#include<cstring>
#include<vector>
#include<cstdio>
using namespace std;
int used[5005],girl[5005],n;
vector<int> line[5005];
int find(int x)
{
    for(int i=0;i<line[x].size();i++)
    {
        if(used[line[x][i]]==0)
        {
            used[line[x][i]]=1;
            if(girl[line[x][i]]==0||find(girl[line[x][i]]))
            {
                girl[line[x][i]]=x;
                return 1;
            }
        }
    }
    return 0;
}
int main()
{
    int T,tot,x,y;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        memset(girl,0,sizeof(girl));
        for(int i=0;i<n;i++)
        {
            line[i].clear();
        }
        for(int i=1;i<=3*n/2;i++)
        {
            scanf("%d %d",&x,&y);
            line[x-1].push_back(y-1);
            line[y-1].push_back(x-1);
        }
        tot=0;
        for(int i=0;i<n;i++)
        {
            memset(used,0,sizeof(used));
            if(find(i))
                tot++;
        }
        printf("%d\n",tot/2);
    }
}

 

上一篇:Maximum Subarray


下一篇:【树直径】CC_MXPATH Maximum Tree Path