日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

【HDU - 1518】Square (经典的dfs + 剪枝)

發(fā)布時間:2023/12/10 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【HDU - 1518】Square (经典的dfs + 剪枝) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

題干:

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 5

Sample Output

yes no yes

題目大意:

給定一些長度各異的木棒,請問是否可能把它們連接成一個正方形?

解題報告:

? ?這題是非常經典的dfs剪枝問題,但是一直弄不懂為什么必須要搞成? ?“一次dfs湊三條邊? ”才可以,不能把dfs的功能限制成 湊一條邊,然后進行三次dfs嗎?(反正我是wa了。。。逃)

ps:與這道經典的剪枝題 相見恨晚啊!!

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 + 剪枝)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。