题解 | #购物单#
购物单
https://www.nowcoder.com/practice/f9c6f980eeec43ef85be20755ddbeaf4
// 1000 5 // 800 2 0 // 400 5 1 // 300 5 1 // 400 3 0 // 500 2 0 const readline = require('readline') const r1= readline.createInterface({ input:process.stdin, output:process.stdout }) let condition = null let lines = [] r1.on('line',(line)=>{ if(!condition){ condition = line.split(' ').map(Number) }else{ lines.push(line.split(' ').map(Number)) if(lines.length===condition[1]){ r1.close() } } }) r1.on('close',()=>{ let [sum,total] = condition sum = sum /10 let map = {} let map2 = {} lines.forEach((item,index)=>{ let price = item[0] let weight = item[0]*item[1] if(!item[2]){ map[index]?map[index]=[[price,weight]]||[]:map[index]=[[price,weight]] }else{ map2[item[2]]?map2[item[2]].push([price,weight]):map2[item[2]] = [[price,weight]] } }) for(let k in map2){ map2[k].forEach(item=>{ let temp = [] map[+k-1].forEach(value=>{ temp.push([value[0]+item[0],value[1]+item[1]]) }) map[+k-1].push(...temp) }) } let newArr = [] for(let k in map){ newArr.push(map[k]) } getMax(sum,newArr) }) function getMax(sum,newArr){ let dp = new Array(newArr.length) for(let i =0;i<dp.length;i++){ dp[i]=new Array(sum+1).fill(0) } for(let i = 0;i<dp[0].length;i++){ let money = 10*i let weight = 0 let arr = newArr[0].filter(item=>{return item[0]<=money}) arr=arr.map(item=>item[1]) if(arr.length>0){ weight = Math.max(...arr) } dp[0][i]=weight } for(let i =1;i<dp.length;i++){ for(let j=1;j<dp[i].length;j++){ let top = dp[i-1][j] let temparr = [] newArr[i].forEach(item=>{ let mp =j-item[0]/10 if(mp>=0){ temparr.push(dp[i-1][mp]+item[1]) } }) dp[i][j] = Math.max(top,...temparr) } } console.log(dp[dp.length-1][dp[0].length-1]) }