Letters比赛第六场1004 Unit Fraction Partition解题报告

1004 Unit Fraction Partition(POJ 1980)

解题思路:DFS + 剪枝。这题的剪枝条件还是比较严格的,很容易超时,我想到的需要剪枝的情况有以下几点:①前几项的和超过了最大值。②前几项的积超过了最大值。③深度超出。④提前“预测”剪枝:即如果剩余的项数乘以当前最小分数要大于剩余的值,则不应该往下搜索。第④点是至关重要的,没有考虑到的话一般会超时。还有可以优化的地方就是避免用实数类型,一是精度难以把握,而是实数运算相对整数运算要慢。

 

代码如下:

 

#include <cstdlib>
#include <iostream>

using namespace std;

int p = 0;
int q = 0;
int a = 0;
int n = 0;
int result = 0;

void DFS(int last, int pt, int qt, int times)
{
    if(times == n+1)
{ return; } int ptt = (a/qt+1)*pt+qt; int qtt = (a/qt+1)*qt; for(int i=a/qt; i>=last; i--) { ptt -= pt; qtt -= qt; if(q*ptt == p*qtt) { result++; return; } else if(q*ptt < p*qtt) { if(ptt*i*q + (n-times)*qtt*q >= p*qtt*i)
{ DFS(i, ptt, qtt, times+1); } } else { return; } } } int main() { #ifdef MYLOCAL freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif while(scanf("%d %d %d %d", &p, &q, &a, &n) != EOF && p+q+a+n) { result = 0; DFS(1, 0, 1, 1); printf("%d\n", result); } return 0; }

 

原文地址:https://www.cnblogs.com/LETTers/p/2469023.html