Find the Marble ZOJ - 3605(三维dp)

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

题意:有n个 杯子,开始时只有一个里面有石头,进行m次两两交换操作,你只能看见其中的k次,问k次之后最可能猜哪个杯子

思路:dp[i][j][x]表示前 i 次交换中看到了 j 次,最后石头的位置在 x 的方案数
不同的i,对于每个j(j需满足比i小,并且比k小),有看见了交换和没看见交换两种情况
没看见:dp[i][j][x]+=dp[i-1][j][x]
看见了:
1.若这一轮(第i轮)进行的操作与这个杯子无关,即x!=a[i] && x!=b[i] 的情况。那么它上一轮结尾时也是x。 dp[i][j][x]+=dp[i-1][j-1][x]
2.若x == a[i],那么它从上一轮结尾为 b[i] 转移,即 dp[i][j][x]+=dp[i-1][j-1][b[i]]
若x==b[i],从上一轮结尾为a[i]转移,即 dp[i][j][x]+=dp[i-1][j-1][a[i]]

#include<bits/stdc++.h>
using namespace std;
#define N 60
typedef long long ll;
ll dp[N][N][N];    //注意结果很大,要用long long存,否则会wa
int a[N];
int b[N];
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));
		dp[0][0][s]=1;
		for(int i=1;i<=m;i++)
			scanf("%d%d",&a[i],&b[i]);
		for(int i=1;i<=m;i++)
		{
			dp[i][0][s]=1;
			for(int j=1;j<=min(i,k);j++)
			{	
				for(int len=1;len<=n;len++)
				{
					dp[i][j][len]+=dp[i-1][j][len];   //没看见,直接继承上一轮的结果
					if(len==a[i])       //看到了,分类讨论
						dp[i][j][a[i]]+=dp[i-1][j-1][b[i]];
					else if(len==b[i])
						dp[i][j][b[i]]+=dp[i-1][j-1][a[i]];
					else
						dp[i][j][len]+=dp[i-1][j-1][len];
				}
			}
		}
		ll ans=dp[m][k][1],u=1;
		for(int i=2;i<=n;i++)
			if(dp[m][k][i]>ans)
			{
				ans=dp[m][k][i];
				u=i;
			}
		cout<<u<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43693379/article/details/91129800
ZOJ