1. 程式人生 > >[SHOI 2008]Debt 循環的債務

[SHOI 2008]Debt 循環的債務

c++ max possible mar pre it is sizeof problem memset

Description

題庫鏈接

A 欠 B \(x_1\) 元, B 欠 C \(x_2\) 元, C 欠 A \(x_3\) 元。現每人手上各有若幹張 100,50,20,10,5,1 鈔票。問至少交換幾張鈔票才能互相還清債務。

\(1\leq |x_1|,|x_2|,|x_3|\leq 1000\) ,總錢數 \(\leq 1000\)

Solution

考慮 \(DP\)

\(f_{i,j,k}\) 為當前考慮第 \(i\) 張鈔票轉移, A 有 \(j\) 元, B 有 \(k\) 元, C 有 \(sum-j-k\) 元。其中 \(sum\) 為三人擁有鈔票價值總和。

\(i\) 張轉移的時候就考慮分錢後每人各有多少張 \(i\)

種鈔票。記得去掉不合法的情況。先從鈔票面值大到小轉移狀態會少些。

Code

//It is made by Awson on 2018.2.27
#include <bits/stdc++.h>
#define LL long long
#define dob complex<double>
#define Abs(a) ((a) < 0 ? (-(a)) : (a))
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Swap(a, b) ((a) ^= (b), (b) ^= (a), (a) ^= (b))
#define writeln(x) (write(x), putchar('\n')) #define lowbit(x) ((x)&(-(x))) using namespace std; const int N = 1000, w[7] = {0, 100, 50, 20, 10, 5, 1}; void read(int &x) { char ch; bool flag = 0; for (ch = getchar(); !isdigit(ch) && ((flag |= (ch == '-')) || 1); ch = getchar()); for
(x = 0; isdigit(ch); x = (x<<1)+(x<<3)+ch-48, ch = getchar()); x *= 1-2*flag; } void print(int x) {if (x > 9) print(x/10); putchar(x%10+48); } void write(int x) {if (x < 0) putchar('-'); print(Abs(x)); } int x1, x2, x3, sum, INF; int a[5][7], cnt[7], tol[5], f[8][N+5][N+5]; void work() { read(x1), read(x2), read(x3); for (int i = 1; i <= 3; i++) for (int j = 1; j <= 6; j++) read(a[i][j]), cnt[j] += a[i][j], tol[i] += a[i][j]*w[j]; sum += tol[1]+tol[2]+tol[3]; memset(f, 127/3, sizeof(f)); INF = f[0][0][0]; f[1][tol[1]][tol[2]] = 0; for (int i = 1; i <= 6; i++) for (int j = 0; j <= sum; j++) for (int k = 0; k+j <= sum; k++) { if (f[i][j][k] == INF) continue; for (int p = 0; p <= cnt[i]; p++) for (int q = 0; p+q <= cnt[i]; q++) { int p1 = j+(p-a[1][i])*w[i], p2 = k+(q-a[2][i])*w[i], p3 = sum-tol[1]-tol[2]+(cnt[i]-p-q-a[3][i])*w[i]; if (p1 < 0 || p2 < 0 || p3 < 0) continue; if (f[i+1][p1][p2] > f[i][j][k]+(Abs(p-a[1][i])+Abs(q-a[2][i])+Abs(cnt[i]-p-q-a[3][i]))/2) f[i+1][p1][p2] = f[i][j][k]+(Abs(p-a[1][i])+Abs(q-a[2][i])+Abs(cnt[i]-p-q-a[3][i]))/2; } } tol[1] -= x1, tol[2] += x1; tol[2] -= x2, tol[3] += x2; tol[3] -= x3, tol[1] += x3; if (tol[1] < 0 || tol[2] < 0 || tol[3] <0 || f[7][tol[1]][tol[2]] == INF) puts("impossible"); else writeln(f[7][tol[1]][tol[2]]); } int main() { work(); return 0; }

[SHOI 2008]Debt 循環的債務