题目: http://codeforces.com/problemset/problem/164/C
题意:
有n个任务,每个任务给定一个开始时间si、持续时间ti、所得收益ci;
有k台机器,每台机器一个时刻只能处理一个任务;
求如何安排,使得收益和最大。
分析:
一个最简单但TLE的建模方法是:
把每个任务拆成两个点ai,bi,在每对(ai,bi)之间建立容量为1,花费为-ci的边;
O(n^2)判两个任务i,j是否不重叠,如果不重叠则连接一条容量为1花费为0的边bi->aj;
超级起点S到各个ai连接容量为1,花费为0的边;
超级终点T到各个bi连接容量为1,花费为0的边;
超级终点T到T‘连接容量为k,花费为0的边。
TLE原因:有n^2规模的边数。
优化建图方案:
将各个时间点离散化,将其作为顶点;
对离散化后第i个时间点,连一条容量为k花费为0的边到第i+1个时间点;
对于一个任务i,在时间点si到si+ti之间建立一条容量为1花费为-ci的边;
再设定一个起点S连接到第一个时间点,容量为k花费为0;
求从S->最后一个时间点的最小费用流并取相反数。
代码:
#include <bits/stdc++.h>
#define Pii pair<int,int>
using namespace std;
typedef long long llong;
const int tmax=2005;
const int INF = 0x7fffffff;
int n,k,num;
struct process{
int s,t,c;
};
process proc[tmax];
set<int> SET;
map<int,int> rrank;
bool ok[tmax];
struct edge{
int to,capacity,cost,rev,who;
edge() {}
edge(int _to,int _capacity,int _cost,int _rev,int _who): to(_to),capacity(_capacity),cost(_cost),rev(_rev),who(_who){}
};
struct Min_Cost_Max_Flow {
int V, H[tmax + 5], dis[tmax + 5], PreV[tmax + 5], PreE[tmax + 5];
vector<edge> G[tmax + 5];
//调用前初始化
void init(int n) {
V = n;
for (int i = 0; i <= V; ++i)G[i].clear();
}
//加边
void add(int from, int to, int cap, int cost,int who) {
G[from].push_back(edge(to, cap, cost, G[to].size(),who));
G[to].push_back(edge(from, 0, -cost, G[from].size() - 1,0));
}
int Min_cost_max_flow(int s, int t, int f, int& flow) {
int res = 0; fill(H, H + 1 + V, 0);
while (f) {
priority_queue <pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q;
fill(dis, dis + 1 + V, INF);
dis[s] = 0; q.push(pair<int, int>(0, s));
while (!q.empty()) {
pair<int, int> now = q.top(); q.pop();
int v = now.second;
if (dis[v] < now.first)continue;
for (int i = 0; i < G[v].size(); ++i) {
edge& e = G[v][i];
if (e.capacity > 0 && dis[e.to] > dis[v] + e.cost + H[v] - H[e.to]) {
dis[e.to] = dis[v] + e.cost + H[v] - H[e.to];
PreV[e.to] = v;
PreE[e.to] = i;
q.push(pair<int, int>(dis[e.to], e.to));
}
}
}
if (dis[t] == INF)break;
for (int i = 0; i <= V; ++i)H[i] += dis[i];
int d = f;
for (int v = t; v != s; v = PreV[v])d = min(d, G[PreV[v]][PreE[v]].capacity);
f -= d; flow += d; res += d*H[t];
for (int v = t; v != s; v = PreV[v]) {
edge& e = G[PreV[v]][PreE[v]];
e.capacity -= d;
G[v][e.rev].capacity += d;
}
}
return res;
}
};
Min_Cost_Max_Flow Network;
int main()
{
int i,j;
scanf("%d%d",&n,&k);
Network.init(2*n+2);
for(i=1;i<=n;i++)
{
scanf("%d%d%d",&proc[i].s,&proc[i].t,&proc[i].c);
SET.insert(proc[i].s);
SET.insert(proc[i].s+proc[i].t);
}
for(set<int>::iterator iter=SET.begin();iter!=SET.end();iter++)
{
rrank[*iter]=++num;
Network.add(num-1,num,k,0,0);
}
for(i=1;i<=n;i++)
Network.add(rrank[proc[i].s],rrank[proc[i].s+proc[i].t],1,-proc[i].c,i);
int flow=0;
Network.Min_cost_max_flow(0,num,INF,flow);
for(int u=0;u<=num;u++)
{
for(i=0;i<Network.G[u].size();i++)
{
edge& e=Network.G[u][i];
if(e.capacity==0&&e.who>0)
ok[e.who]=true;
}
}
for(i=1;i<=n;i++)
if(ok[i]) printf("1 ");
else printf("0 ");
return 0;
}