Advertisement
LinKin

HC Karp

Jun 25th, 2013
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. /* Hopcroft-Karp max maching */
  2. /* O( sqrt(V)*E ) */
  3. /* Spoj 4206. Fast Maximum Matching */
  4.  
  5. #include<stdio.h>
  6. #include<string.h>
  7. #include<vector>
  8. #include<queue>
  9. using namespace std;
  10. #define MAX 100007
  11. #define INF 7777777
  12.  
  13. vector<long> Edge[MAX+7];
  14. long L,R,n,m;   // L->left vertex ; R->Right vertex ; n->Tot vertex(L+R)
  15. long D[MAX+7];  // D->Shortest distance
  16. long M[MAX+7];
  17. /* Node 0 is used as dummy here */
  18. bool Bfs( void )
  19. {
  20.     queue<long> q;
  21.     long i;
  22.     for( i=1;i<=L;i++){
  23.         if( M[i] ) D[i] = INF;
  24.         else{
  25.             D[i] = 0;
  26.             q.push( i );
  27.         }
  28.     }
  29.     D[0] = INF;
  30.     while( !q.empty()){
  31.         long u = q.front();
  32.         q.pop();
  33.         for( i=0;i<Edge[u].size();i++){
  34.             long v = Edge[u][i];
  35.             if( D[M[v]] == INF ){
  36.                 D[M[v]] = D[u] + 1;
  37.                 q.push( M[v] );
  38.             }
  39.         }
  40.     }
  41.     return D[0] != INF;
  42. }
  43. bool Dfs( long u )
  44. {
  45.     if( !u ) return true;
  46.     long i;
  47.     for( i=0;i<Edge[u].size();i++){
  48.         long v = Edge[u][i];
  49.         if( D[M[v]]==D[u]+1 && Dfs( M[v] )){
  50.             M[u] = v;
  51.             M[v] = u;
  52.             return true;
  53.         }
  54.     }
  55.     D[u] = INF;
  56.     return false;
  57. }
  58. int main( void )
  59. {
  60.     long i,j,u,v;
  61.     //freopen("text1.txt","r",stdin );
  62.     scanf("%ld%ld%ld",&L,&R,&m );
  63.     n = L+R;
  64.     for( i=1;i<=m;i++){
  65.         scanf("%ld%ld",&u,&v );
  66.         Edge[u].push_back( L+v );
  67.         Edge[L+v].push_back( u );
  68.     }  
  69.     long Ans = 0;
  70.     while( Bfs()){
  71.         for( i=1;i<=L;i++){
  72.             if( M[i] ) continue;
  73.             if( Dfs( i )){
  74.                 Ans++;
  75.             }
  76.         }
  77.     }
  78.     printf("%ld\n",Ans );
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement