HDU - 5406 CRB and Apple (費用流)
阿新 • • 發佈:2018-09-23
隊列 n+1 ios cos struct names 優化 n) ostream
題意:對於給定的物品,求兩個在高度上單調不遞增,權值上單調不遞減的序列,使二者長度之和最大。
分析:可以用費用流求解,因為要求長度和最大,視作從源點出發的流量為2的費用流,建負權邊,每個物品只能取一次,且花費為-1。將每個物品拆成入點和出點,中間建容量為1,費用為-1的弧。建源點s和超級源點S,S到s建容量為2,費用為0的弧,表示只有兩個序列。源點s向每個入點建容量為1,費用為0的弧,表示每個點都可作為序列的首項。出點向匯點建容量為1,費用為0的弧,表示每個點都可作為序列的末項。
對給定物品按高度和權值排序後,從權值較小的物品向權值較大的物品建邊,容量為1,花費為0。
跑出費用流後對花費取反就是答案。spfa要用棧優化,隊列會T。
#include<iostream> #include<cstring> #include<stdio.h> #include<algorithm> #include<string> #include<cmath> #include<set> #include<map> #include<vector> #include<stack> #include<queue> using namespace std; const int MAXN = 2005; const int MAXM = 2000005; const int INF = 0x3f3f3f3f; struct Edge{ int to, next, cap, flow, cost; } edge[MAXM]; int head[MAXN], tot; int pre[MAXN], dis[MAXN]; bool vis[MAXN]; int N; void init(int n) { N = n; tot = 0; memset(head, -1, sizeof(head)); } void AddEdge(int u, int v, int cap, int cost) { edge[tot] = (Edge){v,head[u],cap,0,cost}; head[u] = tot++; edge[tot] = (Edge){u,head[v],0,0,-cost}; head[v] = tot++; } bool spfa(int s, int t){ stack<int> q; for (int i = 0; i < N; i++){ dis[i] = INF; vis[i] = false; pre[i] = -1; } dis[s] = 0; vis[s] = true; q.push(s); while (!q.empty()){ int u = q.top(); q.pop(); vis[u] = false; for (int i = head[u]; i != -1; i = edge[i].next){ int v = edge[i].to; if (edge[i].cap > edge[i].flow && dis[v] > dis[u] + edge[i].cost){ dis[v] = dis[u] + edge[i].cost; pre[v] = i; if (!vis[v]){ vis[v] = true; q.push(v); } } } } if (pre[t] == -1) return false; else return true; } int minCostMaxflow(int s, int t, int &cost){ int flow = 0; cost = 0; while (spfa(s, t)){ int Min = INF; for (int i = pre[t]; i != -1; i = pre[edge[i ^ 1].to]){ if (Min > edge[i].cap - edge[i].flow) Min = edge[i].cap - edge[i].flow; } for (int i = pre[t]; i != -1; i = pre[edge[i ^ 1].to]){ edge[i].flow += Min; edge[i ^ 1].flow -= Min; cost += edge[i].cost * Min; } flow += Min; } return flow; } struct Node{ int h,w; bool operator<(const Node &rhs) const{ if(h==rhs.h) return w<rhs.w; return h>rhs.h; } }vz[MAXN]; int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); #endif int T; scanf("%d",&T); while(T--){ int N; scanf("%d",&N); int u,v; for(int i=1;i<=N;++i){ scanf("%d %d",&vz[i].h,&vz[i].w); } sort(vz+1,vz+N+1); init(2*N+4); int s = 2*N+1, t = 2*N+2; int S = 0; for(int i=1;i<=N;++i){ AddEdge(i+N,t,1,0); AddEdge(s,i,1,0); AddEdge(i,i+N,1,-1); int x = INF; for(int j=i+1;j<=N;++j){ if(vz[i].w<=vz[j].w){ AddEdge(i+N,j,1,0); } } } AddEdge(S,s,2,0); int cost; minCostMaxflow(S,t,cost); printf("%d\n",-cost); } return 0; }
HDU - 5406 CRB and Apple (費用流)