【HDU - 1518】Square (经典的dfs + 剪枝)
題干:
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square??
Input
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.?
Output
For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".?
Sample Input
3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5Sample Output
yes no yes題目大意:
給定一些長度各異的木棒,請問是否可能把它們連接成一個正方形?解題報告:
? ?這題是非常經(jīng)典的dfs剪枝問題,但是一直弄不懂為什么必須要搞成? ?“一次dfs湊三條邊? ”才可以,不能把dfs的功能限制成 湊一條邊,然后進行三次dfs嗎?(反正我是wa了。。。逃)
ps:與這道經(jīng)典的剪枝題 相見恨晚啊!!
AC代碼:
#include<bits/stdc++.h>using namespace std; int n,sum; int a[55]; bool vis[55];bool dfs(int cur, int st,int res) {if(cur == 4) return 1;if(res < 0) return 0 ;if(res == 0) {int bg = 1;while(vis[bg]) ++bg;for(int i = bg; i<=n; i++) {if(vis[i]) continue;vis[i]=1; if(dfs(cur+1,i+1,sum/4-a[i])) return 1;vis[i]=0;}return 0;} // if(st > n) return 0;for(int i = st; i<=n; i++) {if(vis[i]) continue;vis[i]=1;if(dfs(cur,i+1,res - a[i])) return 1;vis[i]=0;}return 0; } bool cmp(const int & a,const int & b) {return a > b; } int main() {int t;cin>>t;while(t--) {scanf("%d",&n);sum=0;int flag=1;for(int i = 1; i<=n; i++) scanf("%d",a+i),sum+=a[i]; if(sum%4 != 0 ){printf("no\n");continue;}memset(vis,0,sizeof vis);sort(a+1,a+n+1,cmp);if(dfs(1,1,sum/4)) printf("yes\n");else printf("no\n");}return 0 ; }wa代碼:
#include<bits/stdc++.h>using namespace std; int n,sum; int a[55]; bool vis[55];bool dfs(int st,int res) {if(res < 0) return 0 ;if(res == 0) return 1 ;for(int i = st; i<=n; i++) {if(vis[i]) continue;vis[i]=1;if(dfs(i+1,res - a[i])) return 1;vis[i]=0;}return 0; } bool cmp(const int & a,const int & b) {return a > b; } int main() {int t;cin>>t;while(t--) {scanf("%d",&n);sum=0;int flag=1;for(int i = 1; i<=n; i++) scanf("%d",a+i),sum+=a[i]; if(sum%4 != 0 ){printf("no\n");continue;}memset(vis,0,sizeof vis);sort(a+1,a+n+1,cmp);int st = 1;for(int i = 1; i<=3; i++) {while(vis[st]) ++st;if(!dfs(st,sum/4)) {flag=0;break;} }if(flag) printf("yes\n");else printf("no\n");}return 0 ; }ps:
求大神給個解釋,,至今不知道為什么、、、
總結
以上是生活随笔為你收集整理的【HDU - 1518】Square (经典的dfs + 剪枝)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【CodeForces - 202A】L
- 下一篇: 俞敏洪:自己就是农民 守着现金才觉得保险