• 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

  • 相关阅读:
    现代软件工程系列 学生的精彩文章 (5) 其实还是人的问题
    4层结构
    Spring Rich Client Project
    有关“理想”与“现实”的两篇文章
    TechEd归来
    Domain Model
    一次Java出错体验
    真心感谢热心帮助我的朋友
    Tapestry & Groovy
    采用 Domain Model 的架构设计的简单问答
  • 原文地址:https://www.cnblogs.com/yangyh/p/2073899.html
Copyright © 2020-2023  润新知