【BZOJ1318】[Spoj744] Longest Permutation【杂项】

来源:互联网 发布:湘北vs山王球员数据 编辑:程序博客网 时间:2024/05/21 07:00

【题目链接】

因为答案一定包含1,那么枚举每个数,发现1就计算一次。

记录每个数和它相同的数的下一个位置next[i]。

先向后尽量多的取不重复的数。然后再去找前面。

可以发现答案数列中的最大值就是答案数列的长度,假设最大值在1的前面,向前枚举,不断用数去更新最大值,可以得到长度len。

注意要保证i + len - 1 < next[i],不然会重复。

然后判断[i, i + len - 1]的和是否等于len*(len + 1)/2,如果相等,那么符合要求,更新答案。

然后把数列翻转过来再做一遍。

/* Footprints In The Blood Soaked Snow */#include <cstdio>#include <algorithm>using namespace std;typedef long long LL;const int maxn = 101000, inf = 0x3f3f3f3f;int n, last[maxn], next[maxn], ans, num[maxn];LL sum[maxn];bool vis[maxn];inline int iread() {int f = 1, x = 0; char ch = getchar();for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';return f * x;}inline void calc(int x) {int len = 0, r = inf;for(int i = x + 1; i <= n && num[i] != 1; i++)if(!vis[num[i]]) vis[num[i]] = 1;else {r = i;break;}for(int i = x; i >= 1; i--) {if(num[i] == 1 && i != x) break;len = max(len, num[i]);r = min(r, next[i]);if(i + len - 1 < r && i + len - 1 <= n)if(sum[i + len - 1] - sum[i - 1] == (LL)len * (len + 1) >> 1)ans = max(ans, len);}for(int i = x + 1; i <= n && num[i] != 1; i++)vis[num[i]] = 0;}inline void solve() {for(int i = 1; i <= n; i++) last[i] = inf;for(int i = n; i >= 1; i--) {next[i] = last[num[i]];last[num[i]] = i;}for(int i = 1; i <= n; i++) if(num[i] == 1)calc(i);}int main() {n = iread();for(int i = 1; i <= n; i++) sum[i] = sum[i - 1] + (num[i] = iread());solve();reverse(num + 1, num + 1 + n);for(int i = 1; i <= n; i++) sum[i] = sum[i - 1] + num[i];solve();printf("%d\n", ans);return 0;}

0 0
原创粉丝点击