There are three different lathes in a factory namely A,B,C. They are all able to work on all kinds of workpieces. And there are n workpieces to be processed, denoted by 1,2,..,n.
Due to different internal implemetations, for a specific workpiece i, it costs A a[i] seconds to finish the job on it while B takes b[i] and C takes c[i] seconds. Each lathe can work on at most one workpiece a time.
Additionally, the Boss is so stingy that he didn't want his lathes to be disengaged at any time before the end of the work. That is:
1. there should not be a time when one of the lathes is in leisure.
2. all lathes should stop simultaneously,and start from time 0.
Your task is to find if there exists an arrangement meeting with the constraints above. if there is,output the minimal time needed to process all the workpieces. Output a line NO else.
Input
There are multiple test cases. The first line of each case is an integer N(0 < N ≤ 40 ) , followed by N lines. In the following N lines, line i contains three integer,a[i],b[i],c[i] (0 < a[i],b[i],c[i] ≤ 120 && 0 < sum(a[i]),sum(b[i]),sum(c[i]) ≤ 120 ) indicating the seconds A,B,C takes to process workpiece i.
Output
Output one line the minimal seconds it takes to process all workpieces within the constraints if there is an arrangement. Print NO if not.
Sample Input
3 7 1 2 1 7 1 1 3 7 2 1 2 3 3 2 1
Sample Output
1 NO
//
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
const int M=122;
int used[M][M][M];
struct Tqu
{
int n;
int l[3];
Tqu () {}
Tqu (int tn,int ta,int tb,int tc)
{
n=tn;l[0]=ta;l[1]=tb;l[2]=tc;
}
};
queue<Tqu> Q;
int n;
int ls[50][3];
int main()
{
while (scanf("%d",&n)!=EOF)
{
int ans=100000000;
memset(used,-1,sizeof(used));
for (int i=0;i<n;++i)
{
for (int j=0;j<3;++j)
scanf("%d",&ls[i][j]);
}
used[ls[0][0]][0][0]=0;Q.push(Tqu(0,ls[0][0],0,0));
used[0][ls[0][1]][0]=0;Q.push(Tqu(0,0,ls[0][1],0));
used[0][0][ls[0][2]]=0;Q.push(Tqu(0,0,0,ls[0][2]));
while (!Q.empty())
{
Tqu now=Q.front();
Q.pop();
if (now.n==n-1)
{
if (now.l[0]==now.l[1]&&now.l[0]==now.l[2]&&now.l[0]<ans)
ans=now.l[0];
continue;
}
int tn=now.n+1;
int a=now.l[0],b=now.l[1],c=now.l[2];
if (used[a+ls[tn][0]][b][c]!=tn)
{
used[a+ls[tn][0]][b][c]=tn;
Q.push(Tqu(tn,a+ls[tn][0],b,c));
}
if (used[a][b+ls[tn][1]][c]!=tn)
{
used[a][b+ls[tn][1]][c]=tn;
Q.push(Tqu(tn,a,b+ls[tn][1],c));
}
if (used[a][b][c+ls[tn][2]]!=tn)
{
used[a][b][c+ls[tn][2]]=tn;
Q.push(Tqu(tn,a,b,c+ls[tn][2]));
}
}
if (ans==100000000) puts("NO");
else printf("%d\n",ans);
}
return 0;
}