s到每个人容量为1,费用为0的边
每个人到每个视频建容量为1, 费用为0的边
每个视频拆点,建容量为1,费用为-w的边
视频之间若时间不覆盖,则容量为1的边,若两视频op相同,费用为W, 否则为0
每个视频到t建容量为1, 费用为0的边
跑一遍s-t最小费用流,答案取负即可
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 1000;
const int INF = 0x3f3f3f3f;
struct Edge {
int from, to, cap, flow, cost;
};
struct MCMF {
int n, m, s, t;
vector<Edge> edges;
vector<int> G[maxn];
int inq[maxn];
int d[maxn];
int p[maxn];
int a[maxn];
void init(int n) {
this->n = n;
for (int i = 0; i < n; i++) G[i].clear();
edges.clear();
}
void addedge(int from, int to, int cap, int cost) {
edges.push_back((Edge){from, to, cap, 0, cost});
edges.push_back((Edge){to, from, 0, 0, -cost});
m = edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
bool BellmanFord(int s, int t, int &flow, int &cost) {
for (int i = 0; i < n; i++) d[i] = INF;
memset(inq, 0, sizeof(inq));
d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF;
queue<int> q;
q.push(s);
while (!q.empty()) {
int u = q.front(); q.pop();
inq[u] = 0;
for (int i = 0; i < G[u].size(); i++) {
Edge &e = edges[G[u][i]];
if (e.cap > e.flow && d[e.to] > d[u] + e.cost) {
d[e.to] = d[u] + e.cost;
p[e.to] = G[u][i];
a[e.to] = min(a[u], e.cap - e.flow);
if (!inq[e.to]) { q.push(e.to); inq[e.to] = 1; }
}
}
}
if (d[t] == INF) return false;
flow += a[t];
cost += d[t] * a[t];
int u = t;
while (u != s) {
edges[p[u]].flow += a[t];
edges[p[u]^1].flow -= a[t];
u = edges[p[u]].from;
}
return true;
}
int mincost(int s, int t) {
int flow = 0, cost = 0;
while (BellmanFord(s, t, flow, cost));
return cost;
}
}mcmf;
struct Data {
int s, t, w, op;
bool operator < (const Data &atr) const {
return s < atr.s;
}
}data[maxn];
int main() {
int T, n, m, k, W;
scanf("%d", &T);
while (T--) {
scanf("%d%d%d%d", &n, &m, &k, &W);
mcmf.init(k+2*m+5);
int s = 0, t = k + 2*m + 1;
for (int i = 1; i <= k; i++) mcmf.addedge(s, i, 1, 0);
for (int i = 0; i < m; i++) {
scanf("%d%d%d%d", &data[i].s, &data[i].t, &data[i].w, &data[i].op);
}
sort(data, data + m);
for (int i = 1; i <= k; i++) {
for (int j = 0; j < m; j++) {
mcmf.addedge(i, k+2*j+1, 1, 0);
}
}
for (int i = 0; i < m; i++) mcmf.addedge(k+i*2+1, k+i*2+2, 1, -data[i].w);
for (int i = 0; i < m; i++) {
for (int j = i + 1; j < m; j++) {
if (data[i].t <= data[j].s || data[i].s >= data[j].t) {
if (data[i].op == data[j].op) {
mcmf.addedge(k+i*2+2, k+j*2+1, 1, W);
}
else {
mcmf.addedge(k+i*2+2, k+j*2+1, 1, 0);
}
}
}
}
for (int i = 0; i < m; i++) {
mcmf.addedge(k+i*2+2, t, 1, 0);
}
printf("%d\n", -mcmf.mincost(s, t));
}
return 0;
}