一、题目
1、题目描述
After the regional contest, all the ACMers are walking alone a very long avenue to the dining hall in groups. Groups can vary in size for kinds of reasons, which means, several players could walk together, forming a group.
As the leader of the volunteers, you want to know where each player is. So you call every player on the road, and get the reply like “Well, there are Ai players in front of our group, as well as Bi players are following us.” from the ith player.
You may assume that only N players walk in their way, and you get N information, one from each player.
When you collected all the information, you found that you’re provided with wrong information. You would like to figure out, in the best situation, the number of people who provide correct information. By saying “the best situation” we mean as many people as possible are providing correct information.
2、接口描述
2.1输入
There’re several test cases.
In each test case, the first line contains a single integer N (1 <= N <= 500) denoting the number of players along the avenue. The following N lines specify the players. Each of them contains two integers Ai and Bi (0 <= Ai,Bi < N) separated by single spaces.
Please process until EOF (End Of File).3 2 0 0 2 2 2 3 2 0 0 2 2 2
2.2输出
For each test case your program should output a single integer M, the maximum number of players providing correct information.
Sample Output
2 2
3、原题链接
Problem - 4293 (hdu.edu.cn)
二、解题报告
1、思路分析
读了题目之后只觉倍感抽象,很怪异,几番思索后,才有思路。
我们将正在行进的这个队伍从前到后依次编号1~n
那么对于回答前面有a个人,后面有b个人的这个人,如果他说的是真话,那么这个人只能在区间[a + 1 , n - b]之间,这样一来我们可以把每个人根据回答放到不同的区间内
我们用数组f[a][b]记录说前面有a个人后面有b个人的人的人数,那么我们需要注意f[a][b]的上限为n - a - b,并且对于a + b >= n的回答显然是错误的,我们置之不理。
然后定义状态dp[i],代表编号[1 , i]说真话的人的最大人数,那么转移方程为
dp[i] = max(dp[i], dp[j] + f[j][n - i]),即第i个人可以跟[1 , i - 1]、[2 , i - 1]……的人为一组,那么当给i划分组后,dp[i]显然为组内人数加上dp[j]
代码很短,思路比较抽象
2、复杂度
时间复杂度:O(n^2) 空间复杂度:O(n^2)
3、代码详解
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <functional>
using namespace std;
#define IOTIE ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
const int N = 505;
int dp[N], f[N][N], n;
void solve()
{while (cin >> n){memset(f, 0, sizeof(f)), memset(dp, 0, sizeof(dp));for (int i = 0, a, b; i < n; i++)cin >> a >> b, f[a][b] += (a + b < n && f[a][b] < n - a - b);for (int i = 1; i <= n; i++)for (int j = 0; j < i; j++)dp[i] = max(dp[i], dp[j] + f[j][n - i]);cout << dp[n] << '\n';}
}
int main()
{IOTIEfreopen("in.txt", "r", stdin);int _ = 1;// cin >> _;while (_--){solve();}return 0;
}