UVA 1508 - Equipment 狀態壓縮 枚舉子集 dfs

來源:互聯網
上載者:User

標籤:acm

UVA 1508 - Equipment 狀態壓縮 枚舉子集 dfs

ACM

題目地址:UVA 1508 - Equipment--PDF

題意: 
給出n個5元組,從中選出k組,使得這些組中5個位置,每個位置上最大數之和最大。

分析: 
想了好久...最後還是參考了別人的題解... 
不過思路很棒,值得學習。

由於n的範圍為1,10000,所以從n考慮是很難解出來的。 
於是我們從5元組考慮。 
每組5元組,最後可能被選擇作為和的一部分,就是[11111],即[全部被選中做和]的子集,一共有31種情況。 
我們只要預先處理這31種情況可能得到的最大的和。然後dfs遍曆子集就行了。具體見代碼。

代碼:

/**  Author:      illuz <iilluzen[at]gmail.com>*  File:        1508.cpp*  Create Date: 2014-06-28 20:55:20*  Descripton:   */#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int N = 10010;int n, t, k, ans;int m[5], r[N][5], mmax[40];int dfs(int S, int num) {// find num different subset in S, return the max sumif (num == 0) {return 0;}int tmp = 0;for (int S0 = S; S0; S0 = (S0-1)&S) {tmp = max(tmp, mmax[S0] + dfs((S0^S), num - 1));}return tmp;}int main() {scanf("%d", &t);while (t--) {memset(m, 0, sizeof(m));// inputscanf("%d%d", &n, &k);for (int i = 0; i < n; i++) {for (int j = 0; j < 5; j++) {scanf("%d", &r[i][j]);m[j] = max(m[j], r[i][j]);}}if (k >= 5) {// just the maxint sum = 0;for (int i = 0; i < 5; i++) {sum += m[i];}printf("%d\n", sum);} else {memset(mmax, 0, sizeof(mmax));for (int i = 0; i < n; i++) {// for every onefor (int S = 0; S <= 31; S++) {// every situation, 00000 to 11111int tmp = 0;for (int k = 0; k < 5; k++) {if (S&(1<<k)) {tmp += r[i][k];}mmax[S] = max(mmax[S], tmp);// update the max of every situation}}}printf("%d\n", dfs(31, k));// find the max sum in 11111}}return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.