Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
Re:交了N次还是TLE,跪求大牛,不胜感激In Reply To:交了N次还是TLE,跪求大牛,不胜感激 Posted by:dreamvtkd at 2010-01-27 13:55:22 终于知道哪里错了,没有tle,各位大侠们可以参考一下 剪枝的关键在于,棒子序列递减排序,组合第1个棒子的时候,从0到n-1中搜索,第2个棒子的时候,从1到n-1中搜索,第i个棒子的时候,从第i-1到n-1中搜索 这个剪枝可以大大提高效率 //之前写的是search(0,0,cnt+1),优化后写的是search(cnt,0,cnt+1),改了之后就ac了 #include <iostream> #include <algorithm> using namespace std; int s[65]; int b[65]; int n,d,len,sum; bool search(int k,int res,int cnt) //k表示当前下标数,res表示当前要还要搜索的朩棒长度,cnt表示已经成功搜索的木棒个数 { if (cnt == d) { return true; } if(k >= n) return false; for(int i = k; i < n; ++i) if(!b[i] && s[i] <= len - res && len - res <= sum - cnt*len ) { if (s[i]+res == len && !b[i]) { b[i] = 1; if(search(cnt,0,cnt+1) == true) //剪枝的关键所在,之前写的是search(0,0,cnt+1),结果是TLE return true; b[i] = 0; } if (s[i]+res < len && !b[i]) { b[i] = 1; if(search(i+1,res+s[i],cnt) == true) return true; b[i] = 0; if (res == 0) return false; // 如果最长的没有选到,则无解 } while (i+1<n && s[i] == s[i+1]) //如果当前的不行,则相同的不再搜索,进行剪枝 { ++i; } } return false; } bool cmp(int i,int j) { return i > j; } bool a(int t) { if(t>0) return true; } int main() { freopen("input.txt","r",stdin); while (true) { cin >> n; if (n) { for (int i = 0; i < 65; ++i) { b[i] = 0; } sum = 0; for (int i = 0; i < n; ++i) { cin >> s[i]; sum += s[i]; } sort(s,s+n,cmp); //降序排列 for (int j = s[0]; j <= sum; ++j) { if (sum%j == 0) { d = sum/j; len = j; if (search(0,0,1) == true) { cout << j << endl; break; } } } } else break; } return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator