Title to a nxn lattice, each lattice has numbers, to take a number of numbers from the lattice, eight directions adjacent to the number can not be taken together, ask the number of the largest and how much.
If you look at the line from the first row, you can see which columns in line 1th will affect only the 2nd row, with no effect at all after line 3rd. The decision of line I is only affected by i-1 decision.
So naturally think of state dp--
- Dp[i][s] The collection of columns in the row I of row I is the largest number of S and
- Dp[i][s]=max (Dp[i-1][s ']) + set S number and (S is the valid next line of S ')
Although the topic n is at most, the set S is 215 states, but in fact legal (cannot take the same row adjacent two columns of numbers) set S state only more than 1000. Enumeration can be transferred, in order to ensure the complexity of time to do some preprocessing on the line.
1#include <cstdio>2#include <cstring>3#include <vector>4#include <algorithm>5 using namespacestd;6 intReadChar*&s) {7 intres=-1;8SSCANF (s),"%d",&res);9 while(*s==' ') ++s;Ten while(*s>='0'&& *s<='9') ++s; One while(*s==' ') ++s; A returnRes; - } - intn,a[ the][ the],d[ the][1<< the],sta[1<< the],sn; the BOOLisOKints) { - for(intI=1; i<n; ++i) { - if(((s>>i-1) &1) && ((s>>i) &1))return 0; - } + return 1; - } + BOOLisOKintXinty) { A for(intI=0; i<n; ++i) { at if((x>>i) &1)==0)Continue; - if((y>>i) &1)return 0; - if(i>0&& (y>>i-1) &1))return 0; - if(i<n-1&& (y>>i+1) &1))return 0; - } - return 1; in } - intMain () { to Charstr[1111]; + while(Gets (str) && *str) { -n=0; the Char*S=STR;intT; * while(T=read (s), t!=-1) a[0][n++]=T; $ for(intI=1; i<n; ++i) {Panax NotoginsengGets (str); s=str; - for(intj=0; j<n; ++J) a[i][j]=read (s); the } +sn=0; A for(intI=0; i< (1<<N); ++i) { the if(isOK (i)) sta[sn++]=i; + } -memset (D,0,sizeof(d)); $ for(intI=0; i<sn; ++i) { $ for(intj=0; j<n; ++K) { - if((STA[I]>>J) &1) d[0][sta[i]]+=a[0][j]; - } the } -vector<int> vec[2222];Wuyi for(intI=0; i<sn; ++i) { the for(intj=0; j<sn; ++j) { - if(isOK (Sta[i],sta[j])) Vec[i].push_back (j); Wu } - } About for(intI=1; i<n; ++i) { $ for(intj=0; j<sn; ++j) { - for(intk=0; K!=vec[j].size (); ++k) D[i][sta[j]]=max (d[i][sta[j]],d[i-1][sta[vec[j][k]]); - for(intk=0; k<n; ++k) { - if((sta[j]>>k) &1) d[i][sta[j]]+=A[i][k]; A } + } the } - intres=0; $ for(intI=0; i<sn; ++i) { theRes=max (res,d[n-1][sta[i]]); the } theprintf"%d\n", res); the GetChar (); - } in return 0; the}
HDU2167 Pebbles (Pressure DP)