HDU2444-The Accomodation of Students-判断是否为二分图+ISAP

时间:2024-03-25 23:07:14

要先判断是不是二分图。用黑白染色法。

遇到已经染过的跟当前的颜色相同时就说明不是二分图,也即出现了奇环

 /*--------------------------------------------------------------------------------------*/

 #include <algorithm>
#include <iostream>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map> //debug function for a N*M array
#define debug_map(N,M,G) printf("\n");for(int i=0;i<(N);i++)\
{for(int j=;j<(M);j++){\
printf("%d",G[i][j]);}printf("\n");}
//debug function for int,float,double,etc.
#define debug_var(X) cout<<#X"="<<X<<endl;
#define LL long long
const int INF = 0x3f3f3f3f;
const LL LLINF = 0x3f3f3f3f3f3f3f3f;
/*--------------------------------------------------------------------------------------*/
using namespace std; int N,M,T; const int maxn = ;
const int maxm = ;
struct Edge{
int to,next;
}edge[maxm]; int head[maxn],tot;
void init()
{
tot = ;
memset(head,-,sizeof head);
}
void add_edge(int u,int v)
{
edge[tot].to = v;edge[tot].next = head[u];
head[u] = tot++;
} int linker[maxn];
bool used[maxn];
int uN; bool dfs(int u)
{
for(int i=head[u];~i;i=edge[i].next)
{
int v = edge[i].to;
if(!used[v])
{
used[v] = true;
if(linker[v] == - || dfs(linker[v]))
{
linker[v] = u;
return true;
}
}
}
return false;
}
int hungary()
{
int res = ;
memset(linker,-,sizeof linker);
for(int u=;u<=uN;u++)
{
memset(used,false,sizeof used);
if(dfs(u)) res++;
}
return res/;
} int col[maxn];
bool isBipartite(int u)
{
queue<int> Q;
Q.push(u);
col[u] = ;
while(!Q.empty())
{
int cur = Q.front();Q.pop();
for(int i = head[cur];~i;i=edge[i].next)
{
int v = edge[i].to;
if(col[v] == col[cur]) return false;
if(col[v] != -) continue;
col[v] = !col[cur];
Q.push(v);
}
}
return true;
} int main()
{
while(~scanf("%d%d",&N,&M))
{
init();
uN = N;
for(int i=,u,v;i<M;i++)
{
scanf("%d%d",&u,&v);
add_edge(u,v);
add_edge(v,u);
} bool flag = true;
memset(col,-,sizeof col);
for(int i=;i<=uN;i++) if(col[i] == -)
{
if(!isBipartite(i) ){flag = false;break;}
}
if(flag)
{
printf("%d\n",hungary());
}
else printf("No\n"); }
}