In fact, the retrospective is very simple is the violence + judgment conditions, the conditions of the establishment of continued violence, conditions are not set to return to the next violence, the difficulty is to find the conditions for the establishment,
In my opinion, backtracking is the pruning of violence, to find out the condition of the establishment of the basic solution ...
Ideas:
This question should find out the current bus order and the number of people can get on the train,, I used num Array to mark the number of each station
Post code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int num[10];
struct
{
int x,y,nu;
}node[30];
int m,cnt,max,n,sum;
void solve(int t)
{
for(int i=t; i<m; i++)
{
int flag = 0;
for(int k=node[i].x; k<node[i].y; k++)
{
if(num[k]+node[i].nu > sum)
{
flag = 1;
break;
}
}
if(flag == 0)
{
for(int k=node[i].x; k<node[i].y; k++)
{
num[k]+=node[i].nu;
}
cnt += (node[i].y - node[i].x)*node[i].nu;
if(cnt > max)
max = cnt;
solve(i+1);
for(int k=node[i].x; k<node[i].y; k++)
{
num[k]-=node[i].nu;
}
cnt -= (node[i].y - node[i].x)*node[i].nu;
}
}
return ;
}
int main()
{
int i;
while(scanf("%d%d%d",&sum,&n,&m),n||m||sum)
{
max = cnt = 0;
memset(num,0,sizeof(num));
memset(node,0,sizeof(node));
for(i=0; i<m; i++)
{
scanf("%d%d%d",&node[i].x,&node[i].y,&node[i].nu);
}
solve(0);
printf("%d\n",max);
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
UVA 301 Transportation (backtracking)