http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3605
F - Find the Marble
Time Limit:2000MS Memory Limit:65536KB
Description
Alice and Bob are playing a game. This game is played with several identical pots and one marble. When the game starts, Alice puts the pots in one line and puts the marble in one of the pots. After that, Bob cannot see the inside of the pots. Then Alice makes a sequence of swappings and Bob guesses which pot the marble is in. In each of the swapping, Alice chooses two different pots and swaps their positions.
Unfortunately, Alice’s actions are very fast, so Bob can only catch k of m swappings and regard these k swappings as all actions Alice has performed. Now given the initial pot the marble is in, and the sequence of swappings, you are asked to calculate which pot Bob most possibly guesses. You can assume that Bob missed any of the swappings with equal possibility.
Input
There are several test cases in the input file. The first line of the input file contains an integer N (N ≈ 100), then N cases follow.
The first line of each test case contains 4 integers n, m, k and s(0 < s ≤ n ≤ 50, 0 ≤ k ≤ m ≤ 50), which are the number of pots, the number of swappings Alice makes, the number of swappings Bob catches and index of the initial pot the marble is in. Pots are indexed from 1 to n. Then m lines follow, each of which contains two integers ai and bi (1 ≤ ai, bi ≤ n), telling the two pots Alice swaps in the i-th swapping.
Outout
For each test case, output the pot that Bob most possibly guesses. If there is a tie, output the smallest one.
Sample Input
3
3 1 1 1
1 2
3 1 0 1
1 2
3 3 2 2
2 3
3 2
1 2
Sample Output
2
1
3
这道题之前想到的是搜索,不过果然搜索来做会超时超到回老家,所以就上网查了一下,只需要动态规划就可解决,动态规划只需要用一个状态方程即可解决。
初始化dp[0][0][s] = 1;
状态转移方程:
if(能看见){
if(t == x)
dp[i][j][t] += dp[i-1][j][y];
else if(t == y)
dp[i][j][t] += dp[i-1][j][x]
else
dp[i][j][t] += dp[i-1][j-1][t];
}
代码如下
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<iostream>
#include<stack>
#include<map>
#include<string>
using namespace std;
long long dp[55][55][55];//dp在50*50*50的累加情况下,可能会超出int,所以此处使用long long
struct{
int x, y;
}f[55];
int main(){
int n, m, k, s, t;
scanf("%d", &t);
while(t--){
scanf("%d%d%d%d", &n, &m, &k, &s);
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= m; i++)//交换次数
scanf("%d%d", &f[i].x, &f[i].y);
dp[0][0][s] = 1;//初始化
for(int i = 1; i <= m; i++)//交换次数
for(int j = 0; j <= i; j++)//能看到的次数
for(int t = 1; t <= n; t++){//瓶子数
if(j < i)
if(t == f[i].x)
dp[i][j][t] += dp[i-1][j][f[i].y];
else if(t == f[i].y)
dp[i][j][t] += dp[i-1][j][f[i].x];
else
dp[i][j][t] += dp[i-1][j][t];
if(j > 0)
dp[i][j][t] += dp[i-1][j-1][t];
}
s = 1;
for(int i = 2; i <= n; i++)
if(dp[m][m-k][i] > dp[m][m-k][s])
s = i;
printf("%d\n", s);
}
return 0;
}