题目链接:P4799 [CEOI2015 Day2] 世界冰球锦标赛 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
折半搜索:
1:先搜索左半边的票价和
2:再搜索右半边的票价和
3:找出左半边中<= m - 右半边的票价的数目
- #include
- #include
- #include
- #include
-
- using namespace std;
-
- typedef long long LL;
-
- const int N = 41;
-
- int k;
- LL n, m;
- LL w[N];
- int cntl, cntr;
- LL lefts[1 << (N / 2)], rights[1 << (N / 2)];
-
- void dfs(int u, int k, LL sum, LL res[], int &cnt)
- {
- if (u == k)
- {
- res[cnt ++ ] = sum;
- return ;
- }
-
- if (sum + w[u] <= m) dfs(u + 1, k, sum + w[u], res, cnt);
- dfs(u + 1, k, sum, res, cnt);
- }
-
- int main()
- {
- cin >> n >> m;
- for (int i = 0; i < n; i ++ ) scanf("%lld", &w[i]);
-
- k = n / 2;
-
- dfs(0, k, 0, lefts, cntl);//求左半边票价和
- dfs(k, n, 0, rights, cntr);//求右半边票价和
-
- sort(lefts, lefts + cntl);
-
- LL ans = 0;
- for (int i = 0; i < cntr; i ++ )//找出左半边中<= m - 右半边的票价的数目?
- ans += upper_bound(lefts, lefts + cntl, m - rights[i]) - lefts;
-
- cout << ans << endl;
-
- return 0;
- }