关于dfs的剪枝问题我之前一直是云里雾里的,最后通过做了几道典型的例题,掌握了一些方法,现在将这些题分享给大家。
zoj—Exchange Cards
Here comes the problem, given the card value he plans to get and the cards he has, Mike wants to fix how many ways he can get it. So it's you task to write a program to figure it out.
Input
The problem consists of multiple test cases, terminated by EOF. There's a blank line between two inputs.
The first line of each test case gives n, the value of the card Mike plans to get and m, the number of different kinds of cards Mike has. n will be an integer number between 1 and 1000. m will be an integer number between 1 and 10.
The next m lines give the information of different kinds of cards Mike have. Each line contains two integers, val and num, representing the value of this kind of card, and the number of this kind of card Mike have.
Note: different kinds of cards will have different value, each val and num will be an integer greater than zero.
Output
For each test case, output in one line the number of different ways Mike could exchange for the card he wants. You can be sure that the output will fall into an integer value.
Output a blank line between two test cases.
Sample Input
5 2 2 1 3 1 10 5 10 2 7 2 5 3 2 2 1 5
Sample Output
1 7
#include
#include
int n,m,k;
int a[100010];
int count;
void dfs(int index,int toal)
{
int i,t;
if(toal==n)
{
count++;
return;
}
for(i=index;in)continue;
t=toal+a[i];
dfs(i+1,t);
while(a[i]==a[i+1]&&i+1
#include
int ans,n,k;
int a[15][2];
void dfs(int card,int toal)
{
int val,i;
if(toal==n)
{
ans++;
return;
}
if(toal>n||card>k)return;
for(i=card;i<=k;i++)
{
if(a[i][1]>0)
{
val=a[i][0]+toal;
a[i][1]--;
dfs(i,val);
a[i][1]++;
}
}
}
int main()
{
int i,m;
m=0;
while(scanf("%d%d",&n,&k)!=EOF)
{
ans=0;
for(i=1;i<=k;i++)
{
scanf("%d%d",&a[i][0],&a[i][1]);
}
dfs(1,0);
if(m)printf("\n");
printf("%d\n",ans);
m++;
}
}
Description
Input
Output
Sample Input
4 6 4 3 2 2 1 1
5 3 2 1 1
400 12 50 50 50 50 50 50 25 25 25 25 25 25
0 0
Sample Output
Sums of 4:
4
3+1
2+2
2+1+1
Sums of 5:
NONE
Sums of 400:
50+50+50+50+50+50+25+25+25+25
50+50+50+50+50+25+25+25+25+25+25
代码如下:/*回溯加剪枝(去重)*/
#include
#include
int n,m;
int a[15],vin[15];
int z[15];
int k;
int flag;
void dfs(int index,int toal)
{
int i,t,j;
if(toal==n)
{
flag=1;
if(k==1)
printf("%d\n",z[0]);
else
{
for(j=0;j