天天看點

HDU 3211—— Washing Clothes【分組背包 & 平衡劃分 & 分組01背包】

​​題目傳送門​​

Description

Dearboy was so busy recently that now he has piles of clothes to wash. Luckily, he has a beautiful and hard-working girlfriend to help him. The clothes are in varieties of colors but each piece of them can be seen as of only one color. In order to prevent the clothes from getting dyed in mixed colors, Dearboy and his girlfriend have to finish washing all clothes of one color before going on to those of another color.

From experience Dearboy knows how long each piece of clothes takes one person to wash. Each piece will be washed by either Dearboy or his girlfriend but not both of them. The couple can wash two pieces simultaneously. What is the shortest possible time they need to finish the job?

Input

The input contains several test cases. Each test case begins with a line of two positive integers M and N (M < 10, N < 100), which are the numbers of colors and of clothes. The next line contains M strings which are not longer than 10 characters and do not contain spaces, which the names of the colors. Then follow N lines describing the clothes. Each of these lines contains the time to wash some piece of the clothes (less than 1,000) and its color. Two zeroes follow the last test case.

Output

For each test case output on a separate line the time the couple needs for washing.

Sample Input

3 4

red blue yellow

2 red

3 blue

4 blue

6 red

0 0

Sample Output

題意:

分析:

  • 不同顔色不可一起洗,各種顔色衣服最大值相加就是答案
  • 每種顔色分一組,組内進行01背包
  • 平衡劃分問題,在所有時間中找出和最接近 sum / 2 的最大值;

AC代碼:

#include <iostream>
#include <vector>
#include <utility>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <queue>
#include <stack>
#include <cstdio>
#include <fstream>
#include <set>
using namespace std;
typedef long long ll;

const int INF = 0x3f3f3f;
const int MAXN = 1e5 + 100;

int max(int a, int b, int c) {
  int t = a > b ? a : b;
  return t > c ? t : c;
}
map<string, int>mp;
vector<int>vec[MAXN];
int dp[15][MAXN];
int sum[15];
int main() {
  int kk, n;
  string str;
  int x;
  while (cin >> kk >> n, kk || n) {
    memset(dp, 0, sizeof dp);
    memset(sum, 0, sizeof sum);
    for (int i = 0; i <= kk; i++) {
      vec[i].clear();
    }
    mp.clear();
    for (int i = 1; i <= kk; i++) {
      cin >> str;
      mp[str] = i;
    }
    for (int i = 1; i <= n; i++) {
      cin >> x >> str;
      vec[mp[str]].push_back(x);
      sum[mp[str]] += x;
    }
    int ans = 0;
    for (int k = 1; k <= kk; k++) {
      for (int i = 0; i < vec[k].size(); i++) {
        for (int j = sum[k]+1 / 2; j >= vec[k][i]; j--) {
          dp[k][j] = max(dp[k][j], dp[k][j - vec[k][i]] + vec[k][i]);
        }
      }
      ans += max(sum[k] / 2, sum[k] - dp[k][sum[k] / 2]);
    }
    cout << ans << endl;
  }
  return 0;
}