@(K ACMer) by 题解工厂
题意:
给你一个序列,求序列中长度为3的公比为k的子序列的个数.
分析:
典型的情况数量问题,一看就应该想到用DP去解决,不难想到一个数
x
为结尾的长度为i的子序列等于,以它前面的数
定义:dp[i][j] 以j结尾的长度为i的子序列的个数
有转移方程dp[i][j]=dp[i−1][j/k]
注意这里的数 j/k 必须位于数列中j之前的位置,所以这里实现的时候运用了一个边转移边添加元素的方法,非常经典,且由于树的大小为 109 这里用了map数组来离散化查找,详细见代码
除了DP由于这个子序列的长度仅为3,我们还可以用构造的方法:
枚举数列中的每个元素作为子序列中间的元素 x ,然后分别到左边去查找
x/k 的个数 n 和x∗k 的个数 m <script type="math/tex" id="MathJax-Element-10">m</script>,这样m*n就是以x为中间元素的子序列个数.这里把所有数的存到map中查的时候到map中去查多少个,但是同样要用到边构成边查的技巧,要不然你不能去查这个数之前的x/k出现多少次.
DP的Code:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
map<int, LL> dp[4];
int n, k, v[200000+100];
int main(void)
{
cin >> n >> k;
for (int i = 0; i < n; i++)
scanf("%d", &v[i]);
LL ans = 0;
for (int j = 0; j < n; j++) {
int x = v[j];
if (x % k == 0) {
ans += dp[2][x / k];
dp[2][x] += dp[1][x / k];
}
dp[1][x] += 1;
}
cout << ans << endl;
return 0;
}
构造的Code:
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <iterator>
#include <cmath>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef long long LL;
const int INF = 0x3fffffff, M = 200009;
LL a[M], b[M], c[M];
int main(void)
{
int n, k;
while (~scanf("%d%d", &n, &k)) {
map<long long,long long> m;
memset(a, 0 ,sizeof(a));
memset(b, 0, sizeof(b));
memset(c, 0, sizeof(c));
for (int i = 0; i < n; i++) {
scanf("%I64d", &a[i]);
if (a[i] % k == 0) {
b[i] = m[a[i] / k];
}
m[a[i]]++;
c[i] = m[a[i] * k];
}
LL ans = 0;
for (int i = 0; i < n; i++) {
LL l, ll;
l = b[i];
ll = m[a[i] * k] - c[i];
//if (k == 1) ll--;
ans += l * ll;
}
printf("%I64d\n", ans);
}
return 0;
}