http://acm.pku.edu.cn/JudgeOnline/problem?id=2362
dfs。
#include<iostream> #include<algorithm> using namespace std; #define MAX 21 int n; int len; int parts; int max; int sum; int a[MAX]; bool used[MAX]; bool pt(int a,int b) { return a>b; } //cnt: 当前长度 //tot: 找到几段木棒了 //I:为数组下标 bool dfs(int cnt, int tot, int I) { int i; if(tot == parts) return true; for(i=I; i<n; i++) { if(i && !used[i-1] && a[i-1] == a[i]) continue; if(!used[i]) { if(cnt + a[i] < len) { used[i] = true; if(dfs(cnt+a[i], tot, i+1)) return true; used[i] = false; } else if(cnt + a[i] == len) { used[i] = true; if(dfs(0, tot+1, 0)) return true; used[i] = false; } if(cnt == 0) break; } } return false; } int main() { //freopen("in.txt", "r", stdin); int i, t; scanf("%d", &t); while(t--) { scanf("%d", &n); sum = 0; for(i=0; i<n; i++) { scanf("%d", &a[i]); sum += a[i]; used[i] = false; } sort(a, a+n, pt); len = sum / 4; parts = 4; if(sum % 4 == 0 && dfs(0, 1, 0)) printf("yes/n"); else printf("no/n"); } return 0; }
本文介绍了一个使用深度优先搜索算法解决将木棒分成四等分的数学问题。通过预处理排序和分组逻辑,实现算法在给定条件下判断是否能够成功分割木棒。
284

被折叠的 条评论
为什么被折叠?



