you are given some marbles of n different color. You have to arrange these marbles in a line. The marbles adjacent with same color form a group. In each group there can be 1 to 3 marble. Adjacent group should have different color and size. The first and last group also should have different color and size. You are given the number of each of these n marbles. You have count the number of ways you can arrange them in a line maintaining the above constraints. For example you have 4 red marbles and 4 green marbles. You can arrange them in the following 8 way - GGGRRGRR, GGRGGRRR, GGRRRGGR, GRRGGGRR, RGGRRRGG, RRGGGRRG, RRGRRGGG, RRRGGRGG. Input Input contains multiple number of test cases. The first line contain the number of test cases t (t < 3000). Each of the next line contains one test case. Each test case starts with n (1 ≤ n ≤ 4) the number of different color. Next contains n integers. The i’th integer denotes the number of marble of color i. The number of marbles of any color is within the range 0…7 (inclusive). The color of the marbles are numbered from 1 to n. Output For each test case output contains one integer in one line denoting the number of ways you can arrange the marbles. Sample Input 6 2 3 3 2 4 4 2 6 6 3 3 4 5 3 4 5 6 4 2 3 4 5 Sample Output 0 8 12 174 1234 1440
问题链接:UVA11125 Arrange Some Marbles 问题简述:(略) 问题分析:数学计算问题,用DFS实现。 程序说明:(略) 参考链接:(略) 题记:(略)
AC的C++语言程序如下:
#include <stdio.h>
#include <string.h>
#define N 4
int n, a[N], start, cnt, dp[N][N][N][N][5000];
int dfs(int s, int c)
{
int t = 0;
for (int i = n - 1; i >= 0; i--)
t = t * 8 + a[i];
int d = dp[start][cnt][s][c][t];
if (d == -1) {
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = 1; j < N; j++) {
if (j > a[i]) break;
if (i == s || j == c) continue;
a[i] -= j;
ans += dfs(i, j);
a[i] += j;
}
int flag = 1;
for (int i = 0; i < n; i++)
if (a[i] > 0) {
flag = 0;
break;
}
if (flag)
if (s != start && c != cnt) ans++;
return dp[start][cnt][s][c][t] = ans;
} else
return d;
}
int main()
{
memset(dp, -1, sizeof (dp));
int t;
scanf("%d", &t);
while (t--) {
int sum = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
sum += a[i];
}
int ans = 0;
if (n == 1 || sum == 0)
ans = (n == 1 && sum >= N) ? 0 : 1;
else
for (int i = 0; i < n; i++)
for (int j = 1; j < N; j++) {
if (j > a[i]) break;
start = i, cnt = j;
a[i] -= j;
ans += dfs(i, j);
a[i] += j;
}
printf("%d\n", ans);
}
return 0;
}
|