今天在回寝室之前A的最后一题,是前年多校的一道最小树形图。
老实说,一开始看到这题第一想法,是将所有终点练到超级汇点,然后跑最短路。冷静了一下发现完全搭不上边……
比如说当你学到了某一个课程的level 5 ,那么该课程的level 4 ,level 3都是无消耗可达的。
是的,说到这,学过最小树形图的十有八九都会有思路,将同一课程高level指向低level,消耗为 0 。建立超级汇点连接每一个课程,再将培训班建边,跑一跑朱刘即可。
题意:
小明有n个课程,每个课程有个理想的level,他想通过补课来达到这些level。补课形式是你在a课程达到某一个level,那你补完之后就会在b课程直接达到 另一个level,花费给定。
求最小花费。
思路:
见上。
AC Code
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#define each(i, n) for (int(i) = 0; (i) < (n); (i)++)
#define reach(i, n) for (int(i) = n - 1; (i) >= 0; (i)--)
#define range(i, st, en) for (int(i) = (st); (i) <= (en); (i)++)
#define rrange(i, st, en) for (int(i) = (en); (i) >= (st); (i)--)
#define fill(ary, num) memset((ary), (num), sizeof(ary))
using namespace std;
typedef long long ll;
const int maxn = 605;
const int maxm = 2005;
const int inf = 0x3f3f3f3f;
int in[maxn];
int pre[maxn], vis[maxn], id[maxn];
int prefix[maxn], num[maxn];
struct node {
int u, v;
ll cost;
} edges[maxm << 1];
ll zhuliu(int root, int n, int m)
{
ll res = 0;
int u, v;
while (true) {
each(i, n + 1) in[i] = inf;
each(i, m)
{
u = edges[i].u, v = edges[i].v;
if (u != v && edges[i].cost < in[v]) {
pre[v] = u;
in[v] = edges[i].cost;
}
}
in[root] = 0;
each(i, n) if (in[i] == inf) return -1;
int scc = 0;
fill(id, -1), fill(vis, -1);
each(i, n)
{
res += in[i];
v = i;
while (vis[v] != i && id[v] == -1 && v != root) {
vis[v] = i;
v = pre[v];
}
if (v != root && id[v] == -1) {
for (u = pre[v]; u != v; u = pre[u])
id[u] = scc;
id[v] = scc++;
}
}
if (scc == 0)
break;
each(i, n) if (id[i] == -1) id[i] = scc++;
each(i, m)
{
v = edges[i].v;
edges[i].u = id[edges[i].u];
edges[i].v = id[edges[i].v];
if (edges[i].u != edges[i].v)
edges[i].cost -= in[v];
}
n = scc;
root = id[root];
}
return res;
}
inline int getNum(int a, int b)
{
return prefix[a] + b + 1;
}
int main()
{
int n, m;
while (scanf("%d %d", &n, &m) != EOF && (n || m)) {
int tmp = 0, mn = 0, a, b, c, d, e;
range(i, 1, n)
{
scanf("%d", &tmp);
prefix[i] = prefix[i - 1] + tmp + 1;
edges[mn++] = (node){ 0, prefix[i - 1] + 1, 0 };
}
each(i, m)
{
scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);
edges[mn++] = (node){ getNum(a - 1, b), getNum(c - 1, d), e };
}
range(i, 1, n) rrange(j, prefix[i - 1] + 3, prefix[i]) edges[mn++] = (node){ j, j - 1, 0 };
printf("%lld\n", zhuliu(0, prefix[n] + 1, mn));
}
return 0;
}