您的位置:首页 > Web前端

LightOJ 1237 Cyber Cafe 费用流

2016-07-22 17:25 603 查看
题目:http://www.lightoj.com/volume_showproblem.php?problem=1237

题意:有n个顾客来消费,记录下了他们的进入时间和离开时间,但每个人的进入和离开时间不是一一对应的,而是乱序的。顾客的消费为(T-K)的2次方,T为在店里停留的时间,若消费最高为G,现在假设可以自由对应进入和离开时间,问最少收入和最多收入,时间有可能记错,若记错输出impossible

思路:从进入时间向离开时间连边,注意进入时间要严格小于离开时间,计算好每条边的费用,从源点向进入时间连边,从离开时间向汇点连边,跑一边费用流,求出最小收入。把每条边的费用取负重新建一次图跑费用流,求出最大收入,这是因为取负后求最短路实际是之前的最长路

总结:进入时间要严格小于离开时间,因为这个错了两次

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;

const int N = 210;
const int INF = 0x3f3f3f3f;
struct edge
{
int st, to, cost, cap, next;
}g[N*N*2];
int cnt, head
;
int cas = 0;
int arr
, brr
;
int dis
, pre
;
bool vis
;
void add_edge(int v, int u, int cost, int cap)
{
g[cnt].st = v, g[cnt].to = u, g[cnt].cost = cost, g[cnt].cap = cap, g[cnt].next = head[v], head[v] = cnt++;
g[cnt].st = u, g[cnt].to = v, g[cnt].cost = -cost, g[cnt].cap = 0, g[cnt].next = head[u], head[u] = cnt++;
}
void spfa(int s, int t)
{
memset(dis, 0x3f, sizeof dis);
memset(vis, 0, sizeof vis);
memset(pre, -1, sizeof pre);
queue<int> que;
que.push(s);
dis[s] = 0, vis[s] = true;
while(! que.empty())
{
int v = que.front(); que.pop();
vis[v] = false;
for(int i = head[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(g[i].cap > 0 && dis[u] > dis[v] + g[i].cost)
{
dis[u] = dis[v] + g[i].cost;
pre[u] = i;
if(! vis[u])
que.push(u), vis[u] = true;
}
}
}
}
int cost_flow(int s, int t, int flow)
{
int res = 0;
while(flow > 0)
{
spfa(s, t);
if(dis[t] == INF) return -1;
int d = flow;
for(int i = pre[t]; i != -1; i = pre[g[i].st])
d = min(d, g[i].cap);
flow -= d;
res += d * dis[t];
for(int i = pre[t]; i != -1; i = pre[g[i].st])
g[i].cap -= d, g[i^1].cap += d;
}
return res;
}
int main()
{
int t, n, K, G;
scanf("%d", &t);
while(t--)
{
scanf("%d%d%d", &n, &K, &G);
for(int i = 1; i <= n; i++)
scanf("%d", &arr[i]);
for(int i = 1; i <= n; i++)
scanf("%d", &brr[i]);
cnt = 0;
memset(head, -1, sizeof head);
for(int i = 1; i <= n; i++)
{
add_edge(0, i, 0, 1);
add_edge(n + i, n + n + 1, 0, 1);
for(int j = 1; j <= n; j++)
{
if(brr[j] <= arr[i]) continue;
int cost = ((brr[j] - arr[i]) - K) * ((brr[j] - arr[i]) - K);
if(cost > G) cost = G;
add_edge(i, n + j, cost, 1);
}
}
int res1 = cost_flow(0, n + n + 1, n);
cnt = 0;
memset(head, -1, sizeof head);
for(int i = 1; i <= n; i++)
{
add_edge(0, i, 0, 1);
add_edge(n + i, n + n + 1, 0, 1);
for(int j = 1; j <= n; j++)
{
if(brr[j] <= arr[i]) continue;
int cost = ((brr[j] - arr[i]) - K) * ((brr[j] - arr[i]) - K);
if(cost > G) cost = G;
add_edge(i, n + j, -cost, 1);
}
}
int res2 = cost_flow(0, n + n + 1, n);
if(res1 == -1 || res2 == -1) printf("Case %d: impossible\n", ++cas);
else printf("Case %d: %d %d\n", ++cas, res1, -res2);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: