NC15832. Most Powerful
描述
Recently, researchers on Mars have discovered N powerful atoms. All of them are different. These atoms have some properties. When two of these atoms collide, one of them disappears and a lot of power is produced. Researchers know the way every two atoms perform when collided and the power every two atoms can produce.
You are to write a program to make it most powerful, which means that the sum of power produced during all the collides is maximal.输入描述
There are multiplecases. The first line of each case has an integer N (2 <= N <= 10), whichmeans there are N atoms: A1, A2, ... , AN.Then N lines follow. There are N integers in each line. The j-th integer on thei-th line is the power produced when Ai and Aj collidewith Aj gone. All integers are positive and not larger than 10000.
The last case isfollowed by a 0 in one line.
There will be no morethan 500 cases including no more than 50 large cases that N is 10.
输出描述
Output the maximalpower these N atoms can produce in a line for each case.
示例1
输入:
2 0 4 1 0 3 0 20 1 12 0 1 1 10 0 0
输出:
4 22
C++14(g++5.4) 解法, 执行用时: 15ms, 内存消耗: 436K, 提交时间: 2020-08-09 14:48:59
#include<bits/stdc++.h> #pragma GCC optimize(3,"Ofast","inline") #define Fox ios::sync_with_stdio(false),cin.tie(0),cout.tie(0); using namespace std; const int N=1e4+10; int n,a[12][12],dp[(1<<10)+10]; int main(){ Fox; while(cin>>n && n){ for(int i=0;i<n;i++) for(int j=0;j<n;j++) cin>>a[i][j]; memset(dp,0,sizeof(dp)); for(int i=2;i<(1<<n);i++){ for(int j=0;j<n;j++) if((i>>j)&1){ for(int k=0;k<n;k++) if(((i>>k)&1) && k!=j) dp[i]=max(dp[i],dp[i-(1<<j)]+a[k][j]); } } cout<<dp[(1<<n)-1]<<"\n"; } return 0; }
C++(clang++ 11.0.1) 解法, 执行用时: 18ms, 内存消耗: 288K, 提交时间: 2022-10-03 16:49:03
#include <bits/stdc++.h> using namespace std; const int m=1<<11; int a[11][11], dp[m]; int main() { int n; while (cin >> n && n!=0) { memset(dp, 0, sizeof dp); for (int i = 0; i < n; i++)for (int j = 0; j < n; j++)scanf("%d", &a[i][j]); for (int i = 0; i < (1<<n); i++)for (int j = 0; j < n; j++)if ((i>>j) & 1)for (int k = 0; k < n; k++)if ((i>>k)&1 && j!=k)dp[i] = max(dp[i], dp[i^(1<<j)]+a[k][j]); cout << dp[(1<<n)-1] <<endl; } return 0; }