[SDOI2010]星际竞速

嘟嘟嘟


带权最小边覆盖?
最小边覆盖可以用二分图解决,那带权怎么办?
一时zz想不出来,看了一眼标签发现跑费用流就行。
把每一个点拆成\(i\)\(i'\),源点向\(i\)连容量为1,费用为0的边,\(i'\)向汇点连\((1, 0)\)的边。然后如果\(x\)\(y\)有边\((x < y)\),从\(x\)\(y\)\((1, c)\)的边。
对于每一个点的点权,我刚开始想每一个点都向\(i'\)\((1, a[i])\)的边,但这样会TLE,实际上只用从源点向\(i'\)\((1, a[i])\)的边,因为根据网络流性质,我们可以直接合并这些边。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 2e3 + 5;
const int maxe = 1e7 + 5;
inline ll read()
{
  ll ans = 0;
  char ch = getchar(), last = ' ';
  while(!isdigit(ch)) last = ch, ch = getchar();
  while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
  if(last == '-') ans = -ans;
  return ans;
}
inline void write(ll x)
{
  if(x < 0) x = -x, putchar('-');
  if(x >= 10) write(x / 10);
  putchar(x % 10 + '0');
}

int n, m, t, a[maxn];
struct Edge
{
  int nxt, from, to, cap, cos;
}e[maxe];
int head[maxn], ecnt = -1;
In void addEdge(int x, int y, int w, int c)
{
  e[++ecnt] = (Edge){head[x], x, y, w, c};
  head[x] = ecnt;
  e[++ecnt] = (Edge){head[y], y, x, 0, -c};
  head[y] = ecnt;
}

bool in[maxn];
int dis[maxn], pre[maxn], flow[maxn];
In bool spfa()
{
  Mem(dis, 0x3f), Mem(in, 0);
  dis[0] = 0, flow[0] = INF;
  queue<int> q; q.push(0);
  while(!q.empty())
    {
      int now = q.front(); q.pop(); in[now] = 0;
      for(int i = head[now], v; ~i; i = e[i].nxt)
	{
	  if(dis[v = e[i].to] > dis[now] + e[i].cos && e[i].cap > 0)
	    {
	      dis[v] = dis[now] + e[i].cos;
	      pre[v] = i;
	      flow[v] = min(flow[now], e[i].cap);
	      if(!in[v]) q.push(v), in[v] = 1;
	    }
	}
    }
  return dis[t] ^ INF;
}
int minCost = 0;
In void update()
{
  int x = t;
  while(x)
    {
      int i = pre[x];
      e[i].cap -= flow[t];
      e[i ^ 1].cap += flow[t];
      x = e[i].from;
    }
  minCost += flow[t] * dis[t];
}

In int MCMF()
{
  while(spfa()) update();
  return minCost;
}

int main()
{
  //freopen("ha.in", "r", stdin);
  Mem(head, -1);
  n = read(), m = read(); t = n + n + 1;
  for(int i = 1; i <= n; ++i) a[i] = read();
  for(int i = 1; i <= n; ++i)
    {
      addEdge(0, i, 1, 0), addEdge(i + n, t, 1, 0);
      addEdge(0, i + n, 1, a[i]);
    }
  for(int i = 1; i <= m; ++i)
    {
      int x = read(), y = read(), c = read();
      if(x > y) swap(x, y);
      addEdge(x, y + n, 1, c);
    }
  write(MCMF()), enter;
  return 0;
}
posted @ 2019-05-01 10:39  mrclr  阅读(131)  评论(0编辑  收藏  举报