pku3211 Washing Clothes(动态规划)

类似0-1背包问题的动态规划

 

#include <iostream> using namespace std; /* #include <fstream> ifstream fin("data.txt"); #define cin fin */ int M, N; char colors[10][12]; int clothes[10][101]; int clothnum[10]; int sub[2][100001]; //出现这个差时较大的数 int getcolor(char* str) { int i; for (i=0; i<M; i++) { if (strcmp(str, colors[i]) == 0) return i; } return -1; } int dp(int curcolor) { int end, index, i, j, clo, curtime, minindex; memset(sub[0], 0, sizeof(sub)/2); end = clothes[curcolor][0]; sub[0][end] = end; for (clo=1; clo<clothnum[curcolor]; clo++) { memset(sub[clo%2], 0, sizeof(sub)/2); curtime = clothes[curcolor][clo]; for (i=0; i<=end; i++) { if (sub[(clo+1)%2][i] != 0) { sub[clo%2][i+curtime] = sub[(clo+1)%2][i] + curtime; if (curtime<=i) sub[clo%2][i-curtime] = sub[(clo+1)%2][i]; else sub[clo%2][curtime-i] = sub[(clo+1)%2][i] + curtime - i; } } end += curtime; } for (i=0; i<=end; i++) { if (sub[(clo+1)%2][i] != 0) return sub[(clo+1)%2][i]; } return 0; } int main() { int i, j, time, curcolor; char strClo[12]; while (cin>>M>>N && !(M==0&&N==0)) { for (i=0; i<M; i++) cin >> colors[i]; memset(clothnum, 0, sizeof(clothnum)); memset(clothes, 0, sizeof(clothes)); memset(sub, 0, sizeof(sub)); time = 0; for (i=0; i<N; i++) { cin >> j >> strClo; if (j==0) continue; curcolor = getcolor(strClo); clothes[curcolor][ clothnum[curcolor]++ ] = j; } for (curcolor=0; curcolor<M; curcolor++) time += dp(curcolor); cout << time << endl; } }

你可能感兴趣的:(pku3211 Washing Clothes(动态规划))