You are given N integer sequences A1, A2, ..., AN. Each of these sequences contains Nelements. You should pick N elements, one from each sequence; let's denote the element picked from sequence Ai by Ei. For each i (2 ≤ i ≤ N), Ei should be strictly greater than Ei-1.
Compute the maximum possible value of E1 + E2 + ... + EN. If it's impossible to pick the elements E1, E2, ..., EN, print -1 instead.
Input
- The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
- The first line of each test case contains a single integer N.
- N lines follow. For each valid i, the i-th of these lines contains N space-separated integers Ai1, Ai2, ..., AiN denoting the elements of the sequence Ai.
Output
For each test case, print a single line containing one integer — the maximum sum of picked elements.
Constraints
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 700
- 1 ≤ sum of N in all test-cases ≤ 3700
- 1 ≤ Aij ≤ 109 for each valid i, j
Subtasks
Subtask #1 (18 points): 1 ≤ Aij ≤ N for each valid i, j
Subtask #2 (82 points): original constraints
Example
Input: 1 3 1 2 3 4 5 6 7 8 9 Output: 18
Explanation
Example case 1: To maximise the score, pick 3 from the first row, 6 from the second row and 9 from the third row. The resulting sum is E1+E2+E3 = 3+6+9 = 18.
28-12-2017
1 secs
50000 Bytes
ADA, ASM, BASH, BF, C, CAML, CLOJ, CLPS, CPP 4.3.2, CPP 6.3, CPP14, CS2, D, ERL, FORT, FS, GO, HASK, ICK, ICON, JAVA, JS, kotlin, LISP clisp, LISP sbcl, LUA, NEM, NICE, NODEJS, PAS fpc, PAS gpc, PERL, PERL6, PHP, PIKE, PRLG, PYPY, PYTH, PYTH 3.5, RUBY, rust, SCALA, SCM chicken, SCM guile, SCM qobi, ST, swift, TCL, TEXT, WSPC
典型的动态规划问题,直接DP就能实现。代码如下:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> typedef long long ll; using namespace std; ll n; ll a[710][710]; ll dp[710][710];//使用long long 形式,若用int,则会炸点数据 int main() { int t; scanf("%d",&t); while(t--) { scanf("%lld",&n); for(ll i=0;i<n;i++) { for(ll j=0;j<n;j++) scanf("%lld",&a[i][j]); } for(ll i=0;i<n;i++) sort(a[i],a[i]+n); memset(dp,0,sizeof(dp)); for(ll i=0;i<n;i++) dp[0][i]=a[0][i]; for(ll i=1;i<n;i++) { for(ll j=0;j<n;j++) { ll t=a[i][j]; for(ll k=0;k<n;k++) { if(t>a[i-1][k] && dp[i-1][k]>0) dp[i][j]=max(dp[i][j],dp[i-1][k]+t); } } } ll maxx=0; for(ll i=0;i<n;i++) maxx=max(maxx,dp[n-1][i]); if(maxx==0) printf("-1\n"); else printf("%lld\n",maxx);//该方法因为n最大为700,测试用例子最大时间为980ms,在1000ms限制之内。 } return 0; }