解題思路
求公平容量指派的最佳平均志願值。
每教師容量cap=M/N。狀態為每個教師已分配人數的N維向量,每一維0至cap;向量總和就是已處理學生數。
依學生順序,選擇任一尚有名額的教師,將對應人數加1並加上該生志願值。保留到達同一向量的最小總值。
任何完整合法指派皆對應從全0到全cap的一條路徑,代價等於總志願值;取最小後除以M並精確half-up至兩位。
最多(cap+1)^N狀態,時間 O(MN(cap+1)^N),空間 O((cap+1)^N);N≤6、M≤12。
Step-by-step animation
兩學生皆填AB、每位教師容量1的示例
步驟 1 / 3
步驟 1
示例兩教師,兩學生都填AB,每教師容量1。
學生1:AB
學生2:AB
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
#include <boost/rational.hpp>
using Q = boost::rational<cpp_int>;
Q rat(cpp_int a, cpp_int b) {
if (b < 0) {
a = -a;
b = -b;
}
return Q(a, b);
}
cpp_int abig(cpp_int a) {
return a < 0 ? -a : a;
}
cpp_int ten(int n) {
cpp_int a = 1;
while (n--)
a *= 10;
return a;
}
Q dec(string s) {
auto slash = s.find('/');
if (slash != string::npos)
return Q(cpp_int(s.substr(0, slash)), cpp_int(s.substr(slash + 1)));
bool neg = !s.empty() && s[0] == '-';
if (s[0] == '-' || s[0] == '+')
s.erase(s.begin());
auto p = s.find('.');
int k = p == string::npos ? 0 : s.size() - p - 1;
if (p != string::npos)
s.erase(p, 1);
size_t z = s.find_first_not_of('0');
cpp_int a = z == string::npos ? cpp_int(0) : cpp_int(s.substr(z));
return Q(neg ? -a : a, ten(k));
}
string fixedq(Q q, int digits) {
cpp_int a = q.numerator(), b = q.denominator(), scale = ten(digits);
bool neg = a < 0;
a = abig(a);
cpp_int k = (2 * a * scale + b) / (2 * b);
string s = k.convert_to<string>();
if (digits) {
if (s.size() <= digits)
s = string(digits + 1 - s.size(), '0') + s;
s.insert(s.size() - digits, ".");
}
return (neg && k != 0 ? "-" : "") + s;
}
string finiteq(Q q) {
cpp_int a = q.numerator(), b = q.denominator();
bool neg = a < 0;
a = abig(a);
cpp_int whole = a / b, r = a % b;
string s = whole.convert_to<string>();
if (r != 0) {
s += '.';
while (r != 0) {
r *= 10;
cpp_int z = r / b;
s += char('0' + z.convert_to<int>());
r %= b;
}
}
return (neg ? "-" : "") + s;
}
int main() {
vector<string> a;
string s;
while (cin >> s)
a.push_back(s);
int M = a.size(), N = a[0].size(), cap = M / N, base = cap + 1, total = 1;
vector<int> power(N, 1);
for (int j = 0; j < N; j++) {
power[j] = total;
total *= base;
}
vector<int> d(total, 1000000);
d[0] = 0;
for (int mask = 0; mask < total; mask++) {
int used = 0;
for (int j = 0; j < N; j++)
used += (mask / power[j]) % base;
if (used >= M)
continue;
for (int j = 0; j < N; j++)
if ((mask / power[j]) % base < cap)
d[mask + power[j]] =
min(d[mask + power[j]], d[mask] + (int)a[used].find('A' + j) + 1);
}
cout << fixedq(Q(d.back(), M), 2) << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。