HDU 2444 The Accomodation of Students(判斷是否是二分圖),hduaccomodation

來源:互聯網
上載者:User

HDU 2444 The Accomodation of Students(判斷是否是二分圖),hduaccomodation

題目連結

題意:n個學生,m對關係,每一對互相認識的能住一個房間。問否把這些學生分成兩組,要求每組的學生都互不認識。求最多需要多少個房間。


是否能分成兩組?也就是說判斷是不是二分圖,判斷二分圖的辦法,用染色法

把初始點染成黑色,然後與之相連的染成白色,重複,使路徑黑白相間,

如果當前點的顏色和與他相連點的顏色相同時,則說明這個圖不是二分圖


求最多需要多少個房間?也就是求最大匹配數。


#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>#include <math.h>#define init(a) memset(a,0,sizeof(a))#define PI acos(-1,0)using namespace std;const int maxn = 310;const int maxm = 100001;#define lson left, m, id<<1#define rson m+1, right, id<<1|1#define min(a,b) (a>b)?b:a#define max(a,b) (a>b)?a:bconst int N = 50010;int ma[maxn][maxn];int line[maxn],color[maxn];bool vis[maxn];int k,n,m;bool flag;int DFS(int u){    for(int  v = 1;v<=n;v++)    {        if(ma[u][v]==1 && !vis[v])        {            vis[v] = 1;            if(line[v]==-1 || DFS(line[v]))            {                line[v] = u;                return 1;            }        }    }    return 0;}void dfs(int u,int st){    if(flag == false)        return ;    for(int v = 1;v <= n;v++)    {        if(ma[u][v])    {        if(!color[v])        {            color[v]= -st;//黑染白 / 白染黑            dfs(v,color[v]);        }        else if(color[v]==st)        {            flag = false;            return;        }    }    }}bool judge(){    flag = true;    color[1] = 1 ;//1代表黑色,-1代表白色    dfs(1,1) ;    return flag;}int K_M(){    int ans = 0;    memset(line,-1,sizeof(line));    for(int i  = 1;i<=n;i++)    {        init(vis);        ans += DFS(i);    }    return ans;}int main(){    int a,b;    while(scanf("%d%d",&n,&m)!=EOF)    {        init(ma);        memset(color,0,sizeof(color));        for(int i = 1;i<=m;i++)        {            scanf("%d%d",&a,&b);            ma[a][b]  = 1;        }        if(!judge())        {            puts("No");            continue;        }        int ans = K_M();        printf("%d\n",ans);    }    return 0;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.