标签:
两次记忆化搜索,第一次找最小的gap,第二次找最少的次数。
#include <iostream> #include <cstdio> #include <cstring> using namespace std; const int INF = 0x3f3f3f3f; int n,x; int a[1005]; int b[1005]; int dp[1005][6005]; int abs(int a) { return a > 0 ? a : -a; } int dfs(int cur,int gap) { if(dp[cur][gap] != -1) return dp[cur][gap]; if(cur == n) { return dp[cur][gap] = abs(gap); } int x = dfs(cur + 1,gap + a[cur] - b[cur]); int y = dfs(cur + 1,gap + b[cur] - a[cur]); return dp[cur][gap] = min(x, y); } int dfs2(int cur,int gap) { if(dp[cur][gap] != -1) return dp[cur][gap]; if(cur == n) { if(abs(gap) == x) return dp[cur][gap] = 0; return dp[cur][gap] = INF; } int p = dfs2(cur + 1,gap + a[cur] - b[cur]); int q = dfs2(cur + 1,gap + b[cur] - a[cur]) + 1; return dp[cur][gap] = min(p, q); } int main() { cin >> n; for(int i = 0;i < n;i ++) { scanf("%d%d",&a[i],&b[i]); } memset(dp,-1,sizeof(dp)); x = dfs(0,0); memset(dp,-1,sizeof(dp)); cout << dfs2(0,0) << endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/wangyiming/p/5930422.html