Headmaster's Headache UVA10817

不等不说这道题其实是一个背包类似物

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include    
#include 
#include   
#include  
#include 
#include  
#include 
#include 
#include 
 
using std::priority_queue;
using std::vector;
using std::swap;
using std::stack;
using std::sort;
using std::max;
using std::min;
using std::pair;
using std::map;
using std::string;
using std::cin;
using std::cout;
using std::set;
using std::queue;
using std::string;
using std::istringstream;
using std::make_pair;
using std::greater;
using std::endl;

const int INFI(INT_MAX-100000);

int table[1 << 8][1 << 8];
int cost[110], state[110];

int main()
{
	int s;
	while(scanf("%d", &s), s)
	{
		for(int i = 0; i < (1 << s); ++i)
			for(int j = 0; j < (1 << s); ++j)
				table[i][j] = INFI;
		int m, n;
		scanf("%d%d", &m, &n);
		int tw, fc = 0;
		int st1 = 0, st2 = 0;
		for(int i = 1; i <= m; ++i)
		{
			scanf("%d", &tw);
			fc += tw;
			char tc = getchar();
			while(tc != '\n')
			{
				if(!isdigit(tc))
				{
					tc = getchar();
					continue;
				}
				int temp = 0;
				while(isdigit(tc))
				{
					temp *= 10;
					temp += tc-'0';
					tc = getchar();
				}
				--temp;
				if(st1&(1 << temp))
					st2 |= 1 << temp;
				else
					st1 |= 1 << temp;
			}
		}	
		table[st1][st2] = fc;
		for(int i = 1; i <= n; ++i)
		{
			scanf("%d", cost+i);
			state[i] = 0;
			char tc = getchar();
			while(tc != '\n')
			{
				if(!isdigit(tc))
				{
					tc = getchar();
					continue;
				}
				int temp = 0;
				while(isdigit(tc))
				{
					temp *= 10;
					temp += tc-'0';
					tc = getchar();
				}
				--temp;
				state[i] |= 1 << temp;
			}
		}
		for(int i = 1; i <= n; ++i)
		{
			int ts1, ts2;
			for(int j = (1 << s)-1; j >= 0; --j)
				for(int k = (1 << s)-1; k >= 0; --k)
					if(table[j][k] < INFI)
					{
						ts1 = j|state[i];
						ts2 = (j&state[i])|k;
						table[ts1][ts2] = min(table[ts1][ts2], table[j][k]+cost[i]);
					}
		}
		printf("%d\n", table[(1 << s)-1][(1 << s)-1]);
	}
	return 0;
}


你可能感兴趣的:(动态规划,训练指南)