POJ 2362 / SCAU 2542 Square
2542 Square
时间限制:3000MS 内存限制:65536K
题型: 外判编程题 语言: 无限制
Description
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
输入格式
The first line of input contains N, the number of test cases. Each test case begins with an integer 4 <= M <= 20, the number of sticks. M integers follow; each gives the length of a stick - an integer between 1 and 10,000.
输出格式
For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".
输入样例
3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5
输出样例
yes no yes
来源
Waterloo local 2002.09.21
作者
admin
1 #include<iostream> 2 #include<cstdio> 3 #include<string> 4 #include<cstring> 5 #include<algorithm> 6 #define MAXN 22 7 8 using namespace std; 9 10 int sticks[MAXN]; 11 bool visit[MAXN]; 12 int n, length, sumlen; 13 14 bool cmp(const int& a, const int& b) 15 { 16 return a>b; 17 } 18 19 bool Traverse(int num, int len, int cur) 20 { 21 if(num == 4) return true; 22 for(int i=cur; i<n; ++i) 23 { 24 if(!visit[i] && !(i && !visit[i-1] && sticks[i] == sticks[i-1])) 25 { 26 if(len+sticks[i] == length) 27 { 28 visit[i] = true; 29 if(Traverse(num+1, 0, 0)) return true; 30 visit[i] = false; 31 return false; 32 } 33 else if(len+sticks[i] < length) 34 { 35 visit[i] = true; 36 if(Traverse(num, len+sticks[i], i+1)) return true; 37 visit[i] = false; 38 if(len == 0) return false; 39 } 40 } 41 } 42 return false; 43 } 44 45 46 int main() 47 { 48 #ifndef ONLINE_JUDGE 49 // freopen("F:\\test\\input.txt", "r", stdin); 50 #endif // ONLINE_JUDGE 51 int t; 52 cin>>t; 53 while(t--) 54 { 55 sumlen = 0; 56 cin>>n; 57 for(int i=0; i<n; ++i) 58 { 59 cin>>sticks[i]; 60 sumlen += sticks[i]; 61 } 62 sort(sticks, sticks+n, cmp); 63 length = sumlen/4; 64 if(sumlen%4 || length < sticks[0]) 65 { 66 cout<<"no"<<endl; 67 continue; 68 } 69 memset(visit, false, sizeof(visit)); 70 if(Traverse(0, 0, 0)) cout<<"yes"<<endl; 71 else cout<<"no"<<endl; 72 } 73 return 0; 74 }

更多内容请关注个人微信公众号 物役记 (微信号:materialchains)
作者:雪影蓝枫
本文版权归作者和博客园共有,欢迎转载,未经作者同意须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?