题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=693
大意:有一个n核的处理器, 有m个任务,每个任务在不同时间完成所用的费用是不同的, 但费用是随时间严格递增的(不超时的关键);一个核一次只能处理一个任务, 每个任务都能在一秒内完成;问处理器处理完所有的任务的最少费用。
这道题也没有那么难, 就是有个细节需要注意, 如果不处理, 就会超时。 注意的说完了。 此类型的题最关键的还建图。 我们先建超级源点和汇点; 然后把源点和每个任务建一条边, 容量为1(因为每个任务只能做一次),费用为0; 把每个任务和做完时的时间建一条边,容量还为1, 而费用就为这个任务在此时做完的费用;再把每个时间点与汇点建一条边,容量就为核的数量, 费用为0;这样把图建完,在注意一下细节就搞定了, 我就是没有注意细节超时好多次。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 5000;
const int inf = 0x3f3f3f3f;
struct Edge
{
int from, to, cap, flow, cost;
Edge(int u, int v, int c, int f, int s)
: from(u), to(v), cap(c), flow(f), cost(s) {}
};
struct MCMF
{
int n, m, s, t;
vector<int> G[maxn];
vector<Edge> edges;
bool inq[maxn];
int d[maxn], p[maxn], a[maxn];
void inin(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 spfa(int& flow, int& cost)
{
memset(inq, false, sizeof(inq));
memset(d, 0x3f, sizeof(d));
d[s] = 0, p[s] = 0, a[s] = inf;
queue<int> Q;
Q.push(s);
inq[s] = true;
while(!Q.empty())
{
int x = Q.front();
Q.pop();
inq[x] = false;
for(int i = 0; i < G[x].size(); i++)
{
Edge& e = edges[G[x][i]];
if(e.cap>e.flow && d[e.to]>d[x]+e.cost)
{
d[e.to] = d[x] + e.cost;
p[e.to] = G[x][i];
a[e.to] = min(a[x], e.cap-e.flow);
if(!inq[e.to])
{
Q.push(e.to);
inq[e.to] = true;
}
}
}
}
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 min_cost(int s, int t)
{
this->s = s;
this->t = t;
int flow = 0, cost = 0;
while(spfa(flow, cost));
return cost;
}
};
int main()
{
MCMF solve;
int T, m, n;
scanf("%d", &T);
while(T--)
{
scanf("%d%d", &m, &n);
int k = n/m+1;
int s = 0, t = 2*n+1;
solve.inin(t);
for(int i = 1; i <= n; i++)
solve.AddEdge(s, i, 1, 0);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
int a;
scanf("%d", &a);
if(j <= k)//优化, 此时图的边就会少很多,就不回超时了。
solve.AddEdge(i, j+n, 1, a);
}
solve.AddEdge(i+n, t, m, 0);
}
printf("%d\n", solve.min_cost(s, t));
}
return 0;
}