zoukankan      html  css  js  c++  java
  • hdu 1518 square

    题目的意思是比较明显的,就是现在给你m根木棒,现在让你判断利用这些木棒能不能组成一个正方形。其实也就是看是不是用一些木棒能凑成4条相等的边。of course深搜。自己做的时候各种超时,各种不解关键在于排好序的时候,在组成一条边的时候要么选要么就直接不选了,这一点很重要。具体的分析看下面的程序。

    #include<iostream>
    #include<algorithm>
    using namespace std;
    int stick[25],visited[25];
    int m,traget;
    bool cmp(int a,int b)
    {
    	return a<b;
    }
    //dfs中的变量的含义,current在凑这条边的时候当前长度,time记录到现在凑够几条边了,搜索的范围是k——1.
    bool dfs(int current,int time,int k)
    {
    	if(time==3)
    		return true;
    	for(int i=k;i>=1;i--)
    	{
    		if(visited[i]==0)
    		{
    			visited[i]=1;
    			if(current+stick[i]==traget)
    			{
    				//返回true是必须的,返回true说明这条边是可取的,反之就是这时不加这条边
    				if(dfs(0,time+1,m))
    					return true;
    			}
    			else {
    				if(current+stick[i]<traget)
    					if(dfs(current+stick[i],time,i-1))//这里的i-1是重点,搜索的范围要减一。
    						return true;
    			}
    			//回溯一下。
    			visited[i]=0;
    		}
    	}
    	return false;
    }
    int main()
    {
    	int n,sum,i;
    	cin>>n;
    	while(n--)
    	{
    		sum=0;
    		cin>>m;
    		for(i=1;i<=m;i++)
    		{
    			cin>>stick[i];
    			sum+=stick[i];
    		}
    		memset(visited,0,sizeof(visited));
    		sort(stick+1,stick+1+m,cmp);
    		//木棒长度之和不能被4整除则直接输出no
    		if((sum%4)!=0)
    			cout<<"no"<<endl;
    		else {
    			//每条边的目标长度
    			traget=sum/4;
    			//深搜返回true当然输出yes
    			if(dfs(0,0,m))
    				cout<<"yes"<<endl;
    			else cout<<"no"<<endl;
    		}
    	}
    	return 0;
    }
    
    


     

  • 相关阅读:
    DRF的Filter:字段过滤,查找,排序
    DRF的ViewSet和Router
    DRF的APIView和mixins+GenericAPIView和ListAPIView
    DRF的Serializer和ModelSerializer
    html5中的drag
    excel与json转换
    call和bind的原生实现
    将字符串转化为条形码,在将canvas转化为图片
    JSON与excel之间的相互转化(Vue)
    js实现点击复制,将内容复制至剪贴板
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3100680.html
Copyright © 2011-2022 走看看