国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

hdu 1518(dfs)

2019-11-17 02:42:06
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

hdu 1518(dfs)

題目鏈接 :http://acm.hdu.edu.cn/showPRoblem.php?pid=1518

Square

Problem DescriptionGiven a set of sticks of various lengths, is it possible to join them end-to-end to form a square?

InputThe 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.

OutputFor each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".

Sample Input3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5

Sample Outputyes no yes題意 :給你n條邊,讓你用這些邊組成正方形(不多不少僅n條)。分析 :主要是超時(shí)問(wèn)題,注意優(yōu)化。
 1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5  6 int a[22],vis[22]; 7 int n,m,length;               //length表示要組成的正方形的邊長(zhǎng) 8 int ans,flag; 9 10 void dfs(int cnt,int sum, int k)   //cnt記錄邊數(shù),sum記錄當(dāng)前邊長(zhǎng),k記錄位置11 {12     if (cnt == 3)               //如果有三條邊滿足要求,那么第四條邊一定滿足要求13     {14         flag = 1;15         return ;16     }17     if (sum == length)        //找到滿足要求的邊,邊數(shù)加一,初始化18     {19         cnt++;20         k = 0;21         sum = 0;22     }23     for (int i=k; i<m; i++)24     {25         if (!vis[i] && sum + a[i] <= length)26         {27             vis[i] = 1;28             dfs(cnt, sum+a[i], i+1);29             if (flag)         //優(yōu)化時(shí)間,(當(dāng)找到所有邊之后就一直返回,不需要再把之后的代碼運(yùn)行一遍)30             {31                 return ;32             }33             vis[i] = 0;34         }35     }36 }37 38 int main ()39 {40     scanf ("%d",&n);41     while (n--)42     {43         ans = 0;44         scanf ("%d",&m);45         for (int i=0; i<m; i++)46         {47             scanf ("%d",&a[i]);48             ans += a[i];49         }50         if (ans % 4)              //如果所有邊長(zhǎng)和不是4的倍數(shù),怎樣都不能組成正方形51         {52             printf ("no/n");53             continue ;54         }55         memset(vis, 0, sizeof(vis));56         flag = 0;57         length = ans / 4;     //記錄正方形邊長(zhǎng)58         dfs(0, 0, 0);59         if (flag)60             printf ("yes/n");61         else62             printf ("no/n");63     }64     return 0;65 }
View Code


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 固始县| 松滋市| 洛南县| 池州市| 荥经县| 庐江县| 平利县| 衡东县| 和田县| 秦皇岛市| 福清市| 武定县| 陇川县| 关岭| 东城区| 霍邱县| 察雅县| 来安县| 禄丰县| 陕西省| 大理市| 兰溪市| 洛宁县| 洪湖市| 山东省| 南安市| 射洪县| 上思县| 册亨县| 郧西县| 永兴县| 大关县| 措勤县| 北辰区| 盐池县| 定日县| 丰台区| 九龙县| 永定县| 乐山市| 扬州市|