ACM PKU 1054 The Troublesome Frog 學會剪枝
http://acm.pku.edu.cn/JudgeOnline/problem?id=1054有的說是入門級剪枝,有的說是剪枝條件很強,,呵呵,無論怎樣,今天我終于成功剪枝了. 以前也是做了很久的.
注意qsort和bsearch 的使用
#include "stdio.h"
#include "stdlib.h"
struct PLANT

{
int x, y;
}plant[5001];
int row, col, n;
int cmp(const void *a, const void *b)

{
PLANT *x = (PLANT *)a, *y = (PLANT *)b;
if(x->x == y->x) return x->y - y->y;
return x->x - y->x;
}
void input()

{
int i;
scanf("%d %d", &row, &col);
scanf("%d", &n);
for(i=0; i<n; i++)
scanf("%d %d", &plant[i].x, &plant[i].y);
}
int solve();
int main()

{
input();
qsort(plant, n, sizeof(PLANT), cmp);
int temp = solve();
if(temp > 2) //題目要求 答案一定大于等于3
printf("%d\n", temp);
else
printf("0\n");
return 0;
}
int solve()

{
int max = 0, temp;
int i, j;
PLANT n1, n2, jump, next;
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
temp = 2;
n1 = plant[i];
n2 = plant[j];
jump.x = plant[j].x - plant[i].x;
jump.y = plant[j].y - plant[i].y;
if(n1.x - jump.x > 0 && (n1.y - jump.y >0 && n1.y - jump.y <=col) )
//只能從外面逃入
continue;
if(n1.x + max*jump.x > row || n1.y + max*jump.y > col || n1.y + max*jump.y <= 0)
//超出范圍
continue;
next.x = plant[j].x + jump.x;
next.y = plant[j].y + jump.y;
while(next.x <= row && next.y <= col && next.x > 0 && next.y > 0)
{
PLANT * a = (PLANT *) bsearch( &next, plant, n, sizeof(PLANT), cmp);
//bsearch 二分法
if(a == NULL)
{
temp = 0;
break;
}
temp ++;
next.x += jump.x;
next.y += jump.y;
}
if(temp > max) max = temp;
}
}
return max;
}

