poj2362 - Square
来源:互联网 发布:培育发展新动力优化 编辑:程序博客网 时间:2024/05/28 03:01
想看更多的解题报告: http://blog.csdn.net/wangjian8006/article/details/7870410
转载请注明出处:http://blog.csdn.net/wangjian8006
题目大意:给出n条木棍的长度,将这些木棍头尾相接,问能不能组成一个正方形,如果可以,那么输出yes,否则输出no
解题思路:搜索,加一些剪枝,搜索大致这样描述,将木棍从小到大排序,之后取木棍,如果可以组成一条边,那么再从开始取木棍组边。
直到取到4条边为止
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAXV 25int nStickCount; //木棍个数int nStickLength[MAXV]; //保存每个木棍的长度int nBorderLength; //如果这些木棍可以组成正方形,这是正方形的边长int vis[MAXV]; //标记某条木棍是否被选中int cmp(const void *a,const void *b){return *(int *)a-*(int *)b;}int dfs(int nNowBorderCount,int nExitBorder,int cur){int i;if(nExitBorder == 4){ //如果已经找到了4条边,则直接返回truereturn 1;}if(nNowBorderCount == nBorderLength){ //如果当前木棍总长度等于边的长度return dfs(0,nExitBorder+1,cur); //将当前木棍长度清零,找到边数+1}for(i = cur;i < nStickCount;i ++){ //从cur后面继续找if(!vis[i-1] && nStickLength[i] == nStickLength[i - 1]){ //如果前面一条木棍没被取中,但是当前木棍长度等于前木棍长度,那么不做处理continue;}if(!vis[i]){ //如果此木棍已经被找到,那么不做处理if(nNowBorderCount + nStickLength[i] < nBorderLength){ //下面做递归操作,假设取i这条木棍,如果可以寻找到4条边,那么返回1vis[i] = 1;if(dfs(nNowBorderCount + nStickLength[i],nExitBorder,i+1)){return 1;}vis[i] = 0;}if(nNowBorderCount + nStickLength[i] == nBorderLength){vis[i] = 1;if(dfs(0,nExitBorder + 1,0)){return 1;}vis[i] = 0;}}}return 0; //做以上操作都没结果,那么返回0,找不到}int main(){int Case,i,nSum;scanf("%d",&Case);while(Case--){scanf("%d",&nStickCount);nSum = 0;for(i = 0;i < nStickCount;i++){scanf("%d",&nStickLength[i]);nSum += nStickLength[i];}qsort(nStickLength,nStickCount,sizeof(int),cmp); //将木棍长度从小到大排序if(nSum%4!=0){ //如果总的棍长对4取余不为0,那么肯定不能组成正方形printf("no\n");}else{nBorderLength = nSum/4; //得到如果可以组成正方形,那么算出边长memset(vis,0,sizeof(vis)); //初始化每个木棍没被取中if(dfs(0,0,0)){printf("yes\n");}else{printf("no\n");}}}return 0;}
- poj2362 - Square
- poj2362--square
- POJ2362 Square
- POJ2362 Square
- poj2362 Square
- POJ2362:Square
- poj2362——Square
- POJ2362:Square(DFS)
- HDU1518 & POJ2362 & ZOJ1909 Square
- POJ2362 Square 搜索
- POJ2362《Square》题解
- POJ2362 Square(dfs)
- POJ2362 Square(dfs)
- poj2362 Square DFS剪枝
- poj2362——Square(深搜dfs)
- hdu1518 Square | ZOJ1909 | POJ2362 (dfs + 剪枝)
- Square poj2362深度优先搜索+剪枝
- POJ2362
- 除法表达式(数论初步) By ACReaper
- Debian 5.0.5的介绍与详细安装图解
- MSSQL如何删除字段的所有约束和索引
- windows下查看linux文件的工具--Explore2fs
- vs2010下cppunit 配置和实例
- poj2362 - Square
- VMware中安装CentOS6.4 Minimal并启用共享文件夹
- myeclipse里web project和web service project的区别
- Oracle IMP/EXP 导入导出
- 给定数组a[N]构造数组b[N]——腾讯笔试
- 快速排序算法C++版
- 数组操作
- POJ 3169 Layout
- 快速排序算法的C++实现及随机数组的产生方法