Problem Statement
There is a rectangular table with an integer written in each cell.
Later, Jessie will come and select some cells in such a way that each row and each column contains no more than one selected cell. She will always select the maximum possible number of cells. However, there might be several possible selections of that size.
Larry suggested a hypothesis: "No matter what maximum selection Jessie choses, the sum of the numbers in the selected cells will always be the same."
Given a vector <string> table, check whether Larry's hypothesis is correct and return "CORRECT" or "INCORRECT" (quotes for clarity only).
Definition
Class: SumOfSelectedCells
Method: hypothesis
Parameters: vector <string>
Returns: string
Method signature: string hypothesis(vector <string> table)
(be sure your method is public)
Constraints
- table will contain between 1 and 20 elements, inclusive.
- Each element of table will be contain between 1 and 50 characters, inclusive.
- Each element of table will be a space-separated list of integers.
- Each element of table will contain the same number of entries.
- Each element of table will contain between 1 and 20 entries, inclusive.
- All numbers in the table will be between 1 and 50, inclusive, with no leading zeroes.
Examples
0)
{"5 6 6"}
Returns: "INCORRECT"
Jessie will select exactly one cell. The sum will be either 5 or 6.
1)
{"11 12 13 14",
"21 22 23 24",
"31 32 33 34",
"41 42 43 44"}
Returns: "CORRECT"
There are 4! = 24 possible selections for Jessie, but it can be shown that each of them gives the sum of 1 + 2 + 3 + 4 + 10 + 20 + 30 + 40 = 110.
2)
{"3 7",
"3 7",
"3 7"}
Returns: "CORRECT"
Jessie will select exactly one 3 and exactly one 7 giving a total of 10.
3)
{"1 2 3",
"4 5 6",
"9 8 7"}
Returns: "INCORRECT"
Jessie can get 13 (2 + 4 + 7) or 15 (1 + 6 + 8) or 17 (3 + 5 + 9).
题意是这个样子的,给一个n*m的矩阵,然后取min{n,m}个数要求每行每列最多只取一个数,问随便怎么取是否取的数之和一样。
一个居然没想出来的状态dp,另外,如果状态dp行列不一样的话可以拿0填补……
关键代码
int dp1[(1<<20)+2]; int dp2[(1<<20)+2]; int a[25][25]; int cnt[(1<<20)+2]; class SumOfSelectedCells { public: string hypothesis(vector<string> table) { int k,i,j,n,m,p; n=table.size(); k=0; memset(a,0,sizeof(a)); for (i=0;i<n;i++) { m=0; for (j=0;j<table[i].size();j++) { if (table[i][j]==' ') { a[i][m++]=k; k=0; } else { k=k*10+table[i][j]-'0'; } } a[i][m++]=k; k=0; } memset(dp1,-1,sizeof(dp1)); memset(dp2,-1,sizeof(dp2)); dp1[0]=0; dp2[0]=0; n=m=max(n,m); for (i=0;i<(1<<n);i++) { k=i; cnt[i]=0; while(k!=0) { cnt[i]+=(k&1); k>>=1; } } for (i=0;i<(1<<n);i++) { for (j=0;j<n;j++) { if ((i & (1<<j))!=0) continue; p=i | (1<<j); if (dp1[i]!=-1) { if (dp1[p]!=-1) dp1[p]=min(dp1[p],dp1[i]+a[cnt[i]][j]); else dp1[p]=dp1[i]+a[cnt[i]][j]; } if (dp2[i]!=-1) { if (dp2[p]!=-1) dp2[p]=max(dp2[p],dp2[i]+a[cnt[i]][j]); else dp2[p]=dp2[i]+a[cnt[i]][j]; } } } if (dp1[(1<<n)-1]==dp2[(1<<n)-1]) return "CORRECT"; return "INCORRECT"; } };