Fork me on GitHub

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  }
复制代码

 

posted @   Gifur  阅读(287)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
TOP
点击右上角即可分享
微信分享提示