日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

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

發(fā)布時間:2023/12/10 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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

題目大意:

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

解題報告:

? ?這題是非常經(jīng)典的dfs剪枝問題,但是一直弄不懂為什么必須要搞成? ?“一次dfs湊三條邊? ”才可以,不能把dfs的功能限制成 湊一條邊,然后進(jìn)行三次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:

求大神給個解釋,,至今不知道為什么、、、

總結(jié)

以上是生活随笔為你收集整理的【HDU - 1518】Square (经典的dfs + 剪枝)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

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