BZOJ1433: [ZJOI2009]假期的宿舍

Description

Input

Output

Sample Input
1
3
1 1 0
0 1 0
0 1 1
1 0 0
1 0 0
Sample Output
^_^
HINT
对于30% 的数据满足1 ≤ n ≤ 12。
对于100% 的数据满足1 ≤ n ≤ 50,1 ≤ T ≤ 20。
Source

裸的二分图,左半部分为需要床的人,右半部分为所有的床,直接跑匈牙利算法即可。

#include
#include
#include
using namespace std;
#define isnum(t) (t>=48&&t<=57)
void in(int &x)
{
    int f=1;x=0;char t=getchar();
    while(!isnum(t)){if(t=='-')f=-1;t=getchar();}
    while(isnum(t)){x=x*10+t-48;t=getchar();}
    x*=f;
}
#define N 51
int T,n,m,p,point[2*N],next[2*N*N],to[2*N*N];
bool bed[N],need[N];int vis[2*N],link[2*N];
void add(int from,int to1)
{
    ++m;next[m]=point[from];
    point[from]=m;to[m]=to1;
}
int maxmatch()
{
    int ans=0,q[2*N],pre[2*N];
    memset(link,0xff,sizeof(link));
    memset(vis,0xff,sizeof(vis));
    memset(pre,0,sizeof(pre));
    for (int now=1;now<=n;++now)
    if (link[now]==-1&&need[now])
    {
        int head=0,tail=1;vis[now]=now;
        memset(q,0,sizeof(q));
        q[1]=now;bool flag=0;pre[now]=-1;
        while((headand(!flag))
        {
            int u=q[++head];
            for (int i=point[u];i;i=next[i])
            {
                int v=to[i];
                if (vis[v]!=now)
                {
                    vis[v]=now;
                    q[++tail]=link[v];
                    if (link[v]!=-1) pre[link[v]]=u;
                    else
                    {
                        flag=1;
                        int d=u,e=v;
                        while(d!=-1)
                        {
                            int t=link[d];
                            link[d]=e;
                            link[e]=d;
                            d=pre[d];
                            e=t;
                        }
                    }
                }
                if (flag) break;
            }
        }
        if (link[now]!=-1) ++ans;
        else return -1;
    }
    return ans;
}
int main()
{
    in(T);
    for (;T;--T)
    {
        scanf("%d",&n);m=0;p=0;
        memset(point,0,sizeof(point));
        memset(next,0,sizeof(next));
        memset(to,0,sizeof(to));
        memset(bed,0,sizeof(bed));
        memset(need,0,sizeof(need));
        for (int i=1;i<=n;++i) scanf("%d",&bed[i]);
        for (int i=1;i<=n;++i)
        {
            scanf("%d",&need[i]);
            need[i]^=1;
            if (!bed[i]) need[i]=1;
            if (need[i]) ++p;
        }
        for (int i=1;i<=n;++i)
            for (int j=1;j<=n;++j)
            {
                int x;scanf("%d",&x);
                if (need[i]&&bed[j]&&(x||(i==j)))
                add(i,n+j),add(n+j,i);
            }
        printf("%s\n",maxmatch()==p?"^_^":"T_T");
    }
    return 0;
}

你可能感兴趣的:(刷题)