zoukankan      html  css  js  c++  java
  • [POJ3740] Easy Finding

    Description

    Given a M×N matrix A. (Aij ∈ {0, 1} (0 ≤ i < M, 0 ≤ j < N)), could you find some rows that let every cloumn contains and only contains one 1.

    Input

    There are multiple cases ended by EOF. Test case up to 500.The first line of input is M, N (M ≤ 16, N ≤ 300). The next M lines every line contains N integers separated by space.

    Output

    For each test case, if you could find it output "Yes, I found it", otherwise output "It is impossible" per line.

    Sample Input

    3 3
    0 1 0
    0 0 1
    1 0 0
    4 4
    0 0 0 1
    1 0 0 0
    1 1 0 1
    0 1 0 0
    

    Sample Output

    Yes, I found it
    It is impossible
    

    Source

    POJ Monthly Contest - 2009.08.23, MasterLuo

    题解

    由于行(≤16),所以我们可以把行压缩成二进制,用(l[])记录每一列的(1)出现在那几行,如果有一个(l[i])为空,则不存在解,为了保证每一列的唯一性,我们可以发现,当每一列只有与之匹配的一行时,状态才为(2^n),判断一个数(x)是否为(2^n),只需判断(x)&((x-1))即可。

    #include<iostream>
    #include<cstdio>
    using namespace std;
    
    const int N=18,M=301;
    int n,m,two[N],l[M];
    
    bool Can()
    {
    	for(int i=1;i<=m;++i)
    		if(!l[i]) return 0;
    	return 1;
    }
    
    bool Chk(int nw)
    {
    	int YH;
    	for(int i=1;i<=m;++i)
    	{
    		YH=nw&l[i];
    		if(YH&(YH-1)) return 0;
    	}
    	return 1;
    }
    
    bool Dfs(int id,int nw)//id表示现在是第几列,nw记录用了哪些行
    {
    	if(id>m) return 1;
    	if(nw&l[id]) return Dfs(id+1,nw);
    	for(int i=1;i<=n;++i)
    		if((l[id]&two[i])&&Chk(nw|two[i])&&Dfs(id+1,nw|two[i])) return 1;
    	return 0;
    }
    
    int main()
    {
    	int tmp; bool Ans;
    	two[0]=1; for(int i=1;i<N;++i) two[i]=two[i-1]<<1;
    	while(~scanf("%d%d",&n,&m))
    	{
    		for(int i=1;i<=m;++i) l[i]=0;
    		for(int i=1;i<=n;++i)
    			for(int j=1;j<=m;++j)
    				if(scanf("%d",&tmp)&&tmp) l[j]|=two[i];
    		Ans=0;
    		if(Can()) Ans=Dfs(1,0);
    		if(Ans) puts("Yes, I found it");
    		else puts("It is impossible");
    	}
    	return 0;
    }
    

    本文作者:OItby @ https://www.cnblogs.com/hihocoder/

    未经允许,请勿转载。

  • 相关阅读:
    Lexical Sign Sequence
    (UPCOJ暑期训练)Tally Counters
    (2019hdu多校第十场) Welcome Party
    (2019hdu多校第十场1003) Valentine's Day
    更新,线段树模板(支持相关基本操作)
    linux(deepin)下Clion的安装及环境配置
    2019牛客第7场——C(Governing sand)
    【数论】数论之旅:N!分解素因子及若干问题
    [二分]Kayaking Trip
    [数论之旅]数学定理
  • 原文地址:https://www.cnblogs.com/hihocoder/p/11389705.html
Copyright © 2011-2022 走看看