The Bavarian Beer Party
Time Limit: 6000MS Memory Limit: 65536K
Total Submissions: 1055 Accepted: 395
Description
The professors of the Bayerische Mathematiker Verein have their annual party in the local Biergarten. They are sitting at a round table each with his own pint of beer. As a ceremony each professor raises his pint and toasts one of the other guests in such a way that no arms cross.
Figure 2: Toasting across a table with eight persons:no arms crossing(left), arms crossing(right)
We know that the professors like to toast with someone that is drinking the same brand of beer, and we like to maximize the number of pairs of professors toasting with the same brand , again without crossing arms. Write an algorithm to do this, keeping in mind that every professor should take part in the toasting.
Input
The frist line of the input contains a single number: the number of test cases to follow. Each test case has the following format:
One line with an even number p, satisfying 2 <= p <= 1000: the number of participants
One line with p integers (separated by single spaces) indicating the beer brands fro the consecutive professors( in clockwise order, starting at an arbitrary position). Each value is between 1 and 100 (boudaries included).
Output
For every test case in the input, the output should contain a single number on a single line: the maximum number of non-intersecting toasts of the same beer brand for this test case.
Sample Input
2
6
1 2 2 1 3 3
22
1 7 1 2 4 2 4 9 1 1 9 4 5 9 4 5 6 9 2 1 2 9
Sample Output
3
6
Source
The 2006 Benelux Algorithm Programming Contest
有偶数个人,所有人都必须互相敬酒,而且不能交叉,问在这种情况下,互相敬酒的人牌子相同的最大对数
为了保证一个区间内不想交,首先要保证这个区间的人数必须是偶数,如果区间人数是是奇数,那必定会存在交叉情况。那么在区间DP的时候中间值K也必须保证是2的倍数。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a[1005];
int dp[1005][1005];
int main()
{
int t;
scanf("%d",&t);
while( t-- )
{
int n;
scanf("%d",&n);
for( int i = 1; i <= n; i++ )
scanf("%d",&a[i]);
memset(dp,0,sizeof(dp));
for( int len = 2; len <= n; len+= 2 )
{
for( int i = 1; i + len - 1 <= n; i++ )
{
int j = i + len - 1;
dp[i][j] = dp[i+1][j-1];
if( a[i] == a[j] )
dp[i][j] += 1;
for( int k = i+1; k < j; k += 2 )
dp[i][j] = max( dp[i][j],dp[i][k]+dp[k+1][j]);
}
}
printf("%d\n",dp[1][n]);
}
return 0;
}