Matching Problem 暴力
题意:
给一个序列a,长度为n,序列b,长度为4,求a的子序列中,有多少个长度与b相等且当\(b_i = b_j\) 时 \(a_i\) = \(a_j\)
题解:
因为n<300,所以用了一个三重循环,暴力求解,注意的是,子序列不用去重。
#include <cstdio>
int cnt[310], c[310][310];
int main() {
int n, ans = 0, a[310], b[5];
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
for(int i = 0; i < 4; i++) scanf("%d", &b[i]);
for(int i = n - 1; i >= 0; i--) {
cnt[a[i]]++;
for(int j = 0; j <= n; j++) c[i][j] = cnt[j];//c[i]这个位置到末尾j的数量
}
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
//printf("%d\n", i);
if((b[0] == b[1] && a[i] != a[j]) || (b[0] != b[1] && a[i] == a[j])) continue;
for(int k = j + 1; k < n; k++) {
//printf("%d %d\n", i, j);
if(b[2] == b[1] && a[k] != a[j]) continue;
if(b[2] == b[0] && a[k] != a[i]) continue;
if(b[2] != b[1] && a[k] == a[j]) continue;
if(b[2] != b[0] && a[k] == a[i]) continue;
if(b[3] == b[0]) ans += c[k+1][a[i]];
else if(b[3] == b[1]) ans += c[k+1][a[j]];
else if(b[3] == b[2]) ans += c[k+1][a[k]];
else {
ans += n - k - 1 - c[k+1][a[i]];
if (a[j]!=a[i]) ans -= c[k+1][a[j]];
if (a[k]!=a[i]&&a[k]!=a[j]) ans-=c[k+1][a[k]];
}
}
}
}
printf("%d\n", ans);
return 0;
}
这个是去重了的
#include <cstdio>
#include <algorithm>
using std::min;
int cnt[310], c[310][310];
int vis1[310], vis2[310], vis3[310], vis[310];
int main() {
int n, ans = 0, a[310], b[5], cc = 1;
scanf("%d", &n);
vis[n] = 0;
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
for(int i = 0; i < 4; i++) scanf("%d", &b[i]);
for(int i = n - 1; i >= 0; i--) {
if(cnt[a[i]] == 0) vis[i] = vis[i+1] + 1;
else vis[i] = vis[i+1];
cnt[a[i]]++;
for(int j = 0; j <= n; j++) c[i][j] = cnt[j];
}
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if((b[0] == b[1] && a[i] != a[j]) || (b[0] != b[1] && a[i] == a[j])) continue;
for(int k = j + 1; k < n; k++) {
if(b[2] == b[1] && a[k] != a[j]) continue;
if(b[2] == b[0] && a[k] != a[i]) continue;
if(b[2] != b[1] && a[k] == a[j]) continue;
if(b[2] != b[0] && a[k] == a[i]) continue;
if(vis1[a[i]] != 0 && vis1[a[i]] == vis2[a[j]] && vis2[a[j]] == vis3[a[k]]) continue;
if(b[3] == b[0]) ans += c[k+1][a[i]];
else if(b[3] == b[1]) ans += c[k+1][a[j]];
else if(b[3] == b[2]) ans += c[k+1][a[k]];
else {
if(b[0] != b[1] && b[1] != b[2] && b[0] != b[2]) ans += vis[k+1] - min(1,c[k+1][a[i]]) - min(1,c[k+1][a[j]]) - min(1,c[k+1][a[k]]);
else if(b[0] == b[1] && b[0] != b[2]) ans += vis[k+1] - min(1, c[k+1][a[i]]) - min(1, c[k+1][a[k]]);
else if(b[0] == b[2] && b[0] != b[1]) ans += vis[k+1] - min(1, c[k+1][a[i]]) - min(1, c[k+1][a[j]]);
else if(b[1] == b[2] && b[1] != b[0]) ans += vis[k+1] - min(1, c[k+1][a[i]]) - min(1, c[k+1][a[k]]);
else ans += vis[k+1] - min(1, c[k+1][a[i]]);
}
vis1[a[i]] = vis2[a[j]] = vis3[a[k]] = cc++;
//printf("%d %d %d %d\n", a[i], a[j], a[k], ans);
}
}
}
printf("%d\n", ans);
return 0;
}