【bzoj1520】[POI2006]Szk-Schools 费用流

题目描述

输入

输出

如果有可行解, 输出最小代价,否则输出NIE.

样例输入

5
1 1 2 3
1 1 5 1
3 2 5 5
4 1 5 10
3 3 3 1

样例输出

9


题解

费用流

设xi表示学生,yi表示编号,那么S->xi,容量为1,费用为0;xi->能够使得xi接受的yj,容量为1,费用为按照题目中计算出来的相应费用;yi->T,容量为1,费用为0。

然后跑最小费用最大流即可。

#include <cstdio>
#include <cstring>
#include <queue>
#define N 500
#define M 100000
using namespace std;
queue<int> q;
int head[N] , to[M] , val[M] , cost[M] , next[M] , cnt = 1 , s , t , dis[N] , from[N] , pre[N];
int abs(int x)
{
    return x > 0 ? x : -x;
}
void add(int x , int y , int v , int c)
{
    to[++cnt] = y , val[cnt] = v , cost[cnt] = c , next[cnt] = head[x] , head[x] = cnt;
    to[++cnt] = x , val[cnt] = 0 , cost[cnt] = -c , next[cnt] = head[y] , head[y] = cnt;
}
bool spfa()
{
    int x , i;
    memset(from , -1 , sizeof(from));
    memset(dis , 0x3f , sizeof(dis));
    dis[s] = 0 , q.push(s);
    while(!q.empty())
    {
        x = q.front() , q.pop();
        for(i = head[x] ; i ; i = next[i])
            if(val[i] && dis[to[i]] > dis[x] + cost[i])
                dis[to[i]] = dis[x] + cost[i] , from[to[i]] = x , pre[to[i]] = i , q.push(to[i]);
    }
    return ~from[t];
}
int main()
{
    int n , i , j , m , a , b , k , f = 0 , ans = 0;
    scanf("%d" , &n) , s = 0 , t = 2 * n + 1;
    for(i = 1 ; i <= n ; i ++ )
    {
        scanf("%d%d%d%d" , &m , &a , &b , &k) , add(s , i , 1 , 0) , add(i + n , t , 1 , 0);
        for(j = a ; j <= b ; j ++ ) add(i , j + n , 1 , k * abs(j - m));
    }
    while(spfa())
    {
        k = 0x3f3f3f3f;
        for(i = t ; i != s ; i = from[i]) k = min(k , val[pre[i]]);
        f += k , ans += k * dis[t];
        for(i = t ; i != s ; i = from[i]) val[pre[i]] -= k , val[pre[i] ^ 1] += k;          
    }
    if(f < n) printf("NIE\n");
    else printf("%d\n" , ans);
    return 0;
}

 

 

posted @ 2017-06-13 09:01  GXZlegend  阅读(289)  评论(0编辑  收藏  举报