【 bzoj 2661 】 [BeiJing wc2012]连连看 - 拆点费用流

来源:互联网 发布:ubuntu如何使用cd命令 编辑:程序博客网 时间:2024/05/01 21:48

  每个数i拆成两个点LiRi,连边SLi,RiT流量为1费用为0,每对有关系的数(x,y)连边 LxRy,LyRx流量为1费用为x+y,打个表可以发现边数不会很多,直接跑最大费用最大流。
  

#include <bits/stdc++.h>using namespace std;#define rep(i,a,b) for (int i = a , _ = b ; i <= _ ; i ++)#define per(i,a,b) for (int i = a , _ = b ; i >= _ ; i --)#define fore(i,u)  for (int i = head[u] ; i ; i = nxt[i])inline int rd() {    char c = getchar();    while (!isdigit(c)) c = getchar() ; int x = c - '0';    while (isdigit(c = getchar())) x = x * 10 + c - '0';    return x;}const int maxn = 2017;const int maxm = 500007;const int inf = 1000000000;typedef int arr[maxn];typedef int adj[maxm];arr head , dis , pre , vis , lid , rid;adj fr , to , cap , cost , nxt , flow;queue<int> Q;inline int gcd(int a , int b) { return b ? gcd(b , a % b) : a; }inline int sqr(int x) { return x * x; }inline int _sqrt(int x) {    int t = (int) sqrt(x + 0.5);    if (t * t != x) return -1;    return t;}int A , B , ett , S , T , tot;int mx_cost , mx_flow;void input() {    ett = 1;    A = rd() , B = rd();}inline void ins(int u , int v , int c , int w) {    fr[++ ett] = u , to[ett] = v , cap[ett] = c , cost[ett] = w , nxt[ett] = head[u] , head[u] = ett;    fr[++ ett] = v , to[ett] = u , cap[ett] = 0 , cost[ett] = -w, nxt[ett] = head[v] , head[v] = ett;}bool spfa() {    rep (i , 1 , tot) dis[i] = -inf;    dis[S] = 0 , vis[S] = 1 , pre[S] = 0;    Q.push(S);    while (!Q.empty()) {        int u = Q.front(); Q.pop();        vis[u] = 0;        fore (i , u) if (cap[i] > flow[i]) {            int v = to[i];            if (dis[v] < dis[u] + cost[i]) {                dis[v] = dis[u] + cost[i];                pre[v] = i;                if (!vis[v]) Q.push(v) , vis[v] = 1;            }        }    }    if (dis[T] == -inf) return 0;//  assert(!pre[S]);    int a = inf;    for (int e = pre[T];e;e = pre[fr[e]]) a = min(a , cap[e] - flow[e]);    mx_cost += dis[T] * a , mx_flow += a;    for (int e = pre[T];e;e = pre[fr[e]])        flow[e] += a , flow[e ^ 1] -= a;    return 1;}#define L(x) lid[x]#define R(x) rid[x]//vector<int> lk[maxn];void solve() {    rep (i , A , B) lid[i] = ++ tot , rid[i] = ++ tot;    rep (x , A , B) rep (y , A , x - 1) {        int z = _sqrt(sqr(x) - sqr(y));        if (z == -1 || gcd(z , y) != 1) continue;//      lk[x].push_back(ett + 1);        ins(L(x) , R(y) , 1 , x + y);//      lk[x].push_back(ett + 1);        ins(L(y) , R(x) , 1 , x + y);    }    S = ++ tot , T = ++ tot;    rep (i , A , B) ins(S , L(i) , 1 , 0) , ins(R(i) , T , 1 , 0);    for (;spfa();)/* printf("%d %d\n" , mx_flow , mx_cost)*/;/*  rep (x , A , B) for (int i = 0;i < lk[x].size();i ++) if (cap[lk[x][i]] == flow[lk[x][i]])        printf("%d %d\n" , x , cost[lk[x][i]] - x);*/    printf("%d %d\n" , mx_flow / 2 , mx_cost / 2);}int main() {    #ifndef ONLINE_JUDGE        freopen("data.txt" , "r" , stdin);    #endif    input();    solve();    return 0;}
0 0