问题分析
第一问时LIS,动态规划求解,第二问和第三问用网络最大流解决。
建模方法
首先动态规划求出F[i],表示以第i位为结尾的最长上升序列的长度,求出最长上升序列长度K。
1. 把序列每位i拆成两个点
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MAXN 100010
#define MAXM 10000000+10
#define INF 0x3f3f3f3f
struct Edge
{
int from, to, cap, flow, next;
};
Edge edge[MAXM];
int head[MAXN], cur[MAXN], edgenum;
int dist[MAXN];
bool vis[MAXN];
int N, M,ss,tt;
void init()
{
edgenum = 0;
memset(head, -1, sizeof(head));
}
void addEdge(int u, int v, int w)
{
Edge E1 = {u, v, w, 0, head[u]};
edge[edgenum] = E1;
head[u] = edgenum++;
Edge E2 = {v, u, 0, 0, head[v]};
edge[edgenum] = E2;
head[v] = edgenum++;
}
bool BFS(int s, int t)
{
queue<int> Q;
memset(dist, -1, sizeof(dist));
memset(vis, false, sizeof(vis));
dist[s] = 0;
vis[s] = true;
Q.push(s);
while(!Q.empty())
{
int u = Q.front();
Q.pop();
for(int i = head[u]; i != -1; i = edge[i].next)
{
Edge E = edge[i];
if(!vis[E.to] && E.cap > E.flow)
{
dist[E.to] = dist[u] + 1;
if(E.to == t) return true;
vis[E.to] = true;
Q.push(E.to);
}
}
}
return false;
}
int DFS(int x, int a, int t)
{
if(x == t || a == 0) return a;
int flow = 0, f;
for(int &i = cur[x]; i != -1; i = edge[i].next)
{
Edge &E = edge[i];
if(dist[E.to] == dist[x] + 1 && (f = DFS(E.to, min(a, E.cap - E.flow), t)) > 0)
{
edge[i].flow += f;
edge[i^1].flow -= f;
flow += f;
a -= f;
if(a == 0) break;
}
}
return flow;
}
int Maxflow(int s, int t)
{
int flow = 0;
while(BFS(s, t))
{
memcpy(cur, head, sizeof(head));
flow += DFS(s, INF, t);
}
return flow;
}
int n;
int a[100005];
int dp[100005];
int main()
{
freopen("data.txt","r",stdin);
ios_base::sync_with_stdio(false);
cin >> n;
int s = 0;
int t = n+n+1;
for(int i=1;i<=n;i++)
{
cin >> a[i];
}
dp[1]=1;
for(int i=2;i<=n;i++)
{
dp[i]=1;
for(int j=1;j<i;j++)
{
if(a[i]>=a[j])
{
dp[i] = max(dp[i],dp[j]+1);
}
}
}
int ans = *max_element(dp+1,dp+1+n);
cout << ans<<endl;
init();
for(int i=1;i<=n;i++)
{
addEdge(i,i+n,1);
}
for(int i=1;i<=n;i++)
{
if(dp[i]==ans)
{
addEdge(s,i,1);
}
if(dp[i]==1)
{
addEdge(i+n,t,1);
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<i;j++)
{
if(a[i]>=a[j]&& dp[i] == dp[j]+1)
{
addEdge(i+n,j,1);
}
}
}
cout << Maxflow(s,t)<<endl;
init();
for(int i=1;i<=n;i++)
{
int fl=1;
if(i==1||i==n) fl=INF;
addEdge(i,i+n,fl);
}
for(int i=1;i<=n;i++)
{
if(dp[i]==ans)
{
if(i==n)
addEdge(s,i,INF);
else
addEdge(s,i,1);
}
if(dp[i]==1)
{
if(i==1)
addEdge(i+n,t,INF);
else
addEdge(i+n,t,1);
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<i;j++)
{
if(a[i]>=a[j]&& dp[i] == dp[j]+1)
{
addEdge(i+n,j,1);
}
}
}
cout << Maxflow(s,t)<<endl;
return 0;
}