思路:
先处理出
dp[i]:
d
p
[
i
]
:
以第
i
i
个元素结尾的最长上升子序列的长度。然后只能用一次的,每个点拆成入点和出点,能从上一个状态转移过来的连一条容量为的边,源点连向
dp[i]=1
d
p
[
i
]
=
1
的
i
i
容量为,
dp[i]=ans
d
p
[
i
]
=
a
n
s
的连向汇点容量为
1
1
,求最大流即为第二问答案,第三问把,
xn
x
n
改为可以用无穷次即可,在求下最大流。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
typedef long long ll;
const int maxn = 1e5 + 10;
const int INF = 1e9 + 10;
using namespace std;
struct st {
int to, cap, re;
st(int t = 0, int c = 0, int r = 0) : to(t), cap(c), re(r) {}
};
int n, m, s, t;
vector<st> G[maxn];
int it[maxn], lv[maxn];
void add(int f, int t, int c) {
G[f].push_back(st(t, c, G[t].size()));
G[t].push_back(st(f, 0, G[f].size() - 1));
}
void bfs() {
memset(lv, -1, sizeof(lv));
queue<int> q;
lv[s] = 0;
q.push(s);
while(!q.empty()) {
int u = q.front(); q.pop();
for(int i = 0; i < G[u].size(); i++) {
st &e = G[u][i];
if(e.cap > 0 && lv[e.to] < 0) {
lv[e.to] = lv[u] + 1;
q.push(e.to);
}
}
}
}
int dfs(int v, int t, int f) {
if(v == t) return f;
for(int &i = it[v]; i < G[v].size(); i++) {
st &e = G[v][i];
if(e.cap > 0 && lv[v] < lv[e.to]) {
int d = dfs(e.to, t, min(f, e.cap));
if(d > 0) {
e.cap -= d;
G[e.to][e.re].cap += d;
return d;
}
}
}
return 0;
}
int maxflow() {
int f = 0;
while(1) {
bfs();
if(lv[t] < 0) return f;
memset(it, 0, sizeof(it));
int fl;
while((fl = dfs(s, t, INF)) >0) f += fl;
}
}
int dp[maxn], a[maxn];
void solve(int ans) {
s = 0; t = 2 * n + 1;
for(int i = s; i <= t; i++) G[i].clear();
for(int i = 1; i <= n; i++) {
int k1 = 2 * i - 1, k2 = 2 * i;
add(k1, k2, 1);
if(dp[i] == ans) add(k2, t, 1);
if(dp[i] == 1) add(s, k1, 1);
for(int j = 1; j < i; j++) {
if(dp[j] == dp[i] - 1 && a[j] < a[i]) add(2 * j, k1, 1);
}
}
}
int main() {
scanf("%d", &n);
memset(dp, 0, sizeof dp);
int ans = 1;
for(int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
dp[i] = 1;
for(int j = 1; j < i; j++) {
if(a[i] <= a[j]) continue;
if(dp[j] + 1 < dp[i]) continue;
dp[i] = dp[j] + 1; ans = max(ans, dp[i]);
}
}
int ans1, ans2;
solve(ans);
ans2 = ans1 = maxflow();
add(1, 2, INF);
add(2 * n - 1, 2 * n, INF);
add(s, 1, INF);
if(dp[n] == ans) add(2 * n, t, INF);
ans2 += maxflow();
printf("%d\n%d\n%d\n", ans, ans1, ans2);
return 0;
}