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个杯子, 手速很快的alice进行m次交换, 每次交换任意两个杯子的位置, bob只能看到k次交换, 最开始有一个球在s上, 求在所有情况下bob眼中球出现位置最多次是哪个位置。
解:三维dp, dp[i][j][k]表示前i次交换bob看到j次时球出现在k上的情况数, 有状态转移方程:
dp[i] [j] [a[i]] = dp[i - 1] [j] [a[i]] + dp[i - 1] [j - 1] [b[i]];
对于第i次交换可以选择看见或者不看见, 不看见的话就是dp[i - 1] [j] [a[i]]直接继承第i - 1次交换看见j次在a[i]上的方案数, 看见的话则是dp[i - 1] [j - 1] [b[i]], 将前i - 1次交换看见j - 1次在b[i]上的方案数转移到dp[i][j][a[i]]上, 没毛病。
AC代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int i, j, kk, n, m, k, s, t, p;
int a[55], b[55];
long long ans;
long long dp[55][55][55] = {0};
scanf("%d", &t);
while(t--){
ans = 0;
scanf("%d %d %d %d", &n, &m, &k, &s);
dp[0][0][s] = 1;
for(i = 1;i <= m;i++)
scanf("%d %d", &a[i], &b[i]);
for(i = 1;i <= m;i++){
for(j = 0;j < i;j++)
dp[i][j + 1][a[i]] = dp[i - 1][j][b[i]];
for(j = 0;j < i;j++)
dp[i][j + 1][b[i]] = dp[i - 1][j][a[i]];
for(kk = 1;kk <= n;kk++){
dp[i][0][kk] = dp[i - 1][0][kk];
for(j = 1;j <= i;j++){
dp[i][j][kk] += dp[i - 1][j][kk];
if(kk != a[i] && kk != b[i])
dp[i][j][kk] += dp[i - 1][j - 1][kk];
}
}
}
for(i = 1;i <= n;i++){
if(ans < dp[m][k][i]){
ans = dp[m][k][i];
p = i;
}
}
printf("%d\n", p);
memset(dp, 0, sizeof(dp));
}
return 0;
}