zoukankan      html  css  js  c++  java
  • POJ 2362/DFS:判断是否能形成正方形

    1011简单改一下就OK了

    #include <iostream>
    #include <algorithm>
    using namespace std;
    #define MAX 64
    int sticks[MAX];
    bool used[MAX];
    int stickNum,plen,n;
    
    bool compare(int a, int b)
    {
        return a > b;    
    }
    //从beginIndex号开始匹配,下一步要匹配matchLen的stick,在此之前已经匹配了hasMatch条stick
    bool dfs(int beginIndex,int matchLen,int hasMatch){
    	
    	if(matchLen==0){
    		hasMatch++;
    			
    		if(hasMatch==4){
    		
    			return true;
    		}
    		for(beginIndex=0;used[beginIndex];beginIndex++);
    		used[beginIndex]=true;
    		if(dfs(beginIndex+1,plen-sticks[beginIndex],hasMatch))return true;
    		used[beginIndex]=false;
    		return false;
    	
    	}else{
    		if(beginIndex>n-1)return false;
    		for(int i=beginIndex;i<n;i++){
    			if(used[i])continue;
    			if(sticks[i]>matchLen)continue;
    			if(i>0&&sticks[i]==sticks[i-1]&&!used[i-1])continue;
    			used[i]=true;
    			if(dfs(i+1,matchLen-sticks[i],hasMatch))
    				return true;
    			used[i]=false;
    		}
    	
    	}
    	//
    	return false;
    
    }
    int main(int argc, char* argv[])
    {
    	//freopen("i://in.txt","r",stdin);
    	int sum = 0;
    	bool ok ;
    	int i,j;
    	int c;
    	scanf("%d",&c);
    	for(j=0;j<c;j++){
    		ok = false;
    		scanf("%d",&n);
    		sum=0;
    		for( i=0;i<n;i++){
    			scanf("%d",&sticks[i]);
    			sum += sticks[i];
    		}
    		
    		if(sum%4!=0){
    			ok = false;
    			
    		}else{
    			sort(sticks,sticks+n,compare);
    			plen = sum/4;
    			used[0]=true;
    			if(dfs(0,plen-sticks[0],0)){
    				ok = true;
    			}
    			//used[0]=false;
    		}
    		printf("%s\n",ok?"yes":"no");
    		memset(used,false,sizeof(used));
    	}
    	return 0;
    }

    躲猫猫社团团长 http://t.sina.com.cn/coolria

  • 相关阅读:
    CentOS 7 将 python版本升级为3.x后产生的各种问题
    CentOS 7.0 Firewall防火墙配置
    CentOS7.2+Python3x+Flask部署标准化配置流程
    CentOS 7 下安装 Nginx
    CentOS7下安装python-pip
    CentOS 7 安装字体
    centos中文目录换成英文目录
    搭建typecho个人博客和主题优化
    迭代器与生成器
    装饰器函数
  • 原文地址:https://www.cnblogs.com/yangyh/p/2073899.html
Copyright © 2011-2022 走看看