2019牛客暑期多校訓練營(第二場)F.Partition problem

連接:https://ac.nowcoder.com/acm/contest/882/F
來源:牛客網

c++

Given 2N people, you need to assign each of them into either red team or white team such that each team consists of exactly N people and the total competitive value is maximized.

Total competitive value is the summation of competitive value of each pair of people in different team.

The equivalent equation is  2Ni=12Nj=i+1(vij if i-th person is not in the same team as j-th person else 0)∑i=12N∑j=i+12N(vij if i-th person is not in the same team as j-th person else 0)

輸入描述:

The first line of input contains an integers N.

Following 2N lines each contains 2N space-separated integers vijvij is the j-th value of the i-th line which indicates the competitive value of person i and person j.

* 1N141≤N≤14
* 0vij1090≤vij≤109
* vij=vjivij=vji

輸出描述:

Output one line containing an integer representing the maximum possible total competitive value.
示例1

輸入

1
0 3
3 0

輸出

3

題意:
將n*2我的分爲兩部分,每個人與另一半的每個人貢獻一個權值,求貢獻和的最大值。
思路:
暴力搜索,最壞的複雜度是C(2*14,14),也就是差很少4e7,若是你肯定某一我的在第一部分,還能夠將複雜度除而2
關於算貢獻,你能夠選擇14*14的複雜度,可是確定會T
在搜索的時候,若是n=5,那麼第一次選在第一部分的人就是 1 2 3 4 5.
第二次選在第一部分的人就是 1 2 3 4 6,能夠發現只有一個數字不一樣。
分析一下,其實在整個搜索的過程當中,也會出現不少這樣只差一個的數組。
因而,咱們能夠記錄上一個狀態,經過上個狀態算出當前狀態,這樣能夠減少不少算貢獻的複雜度。
就這樣,個人代碼跑了3700ms以後卡過去了。
#include <bits/stdc++.h>
#define eps 1e-8
#define INF 0x3f3f3f3f
#define PI acos(-1)
#define lson l,mid,rt<<1
#define rson mid+1,r,(rt<<1)+1
#define CLR(x,y) memset((x),y,sizeof(x))
#define fuck(x) cerr << #x << "=" << x << endl;
using namespace std; typedef long long ll; typedef unsigned long long ull; const int seed = 131; const int maxn = 1e5 + 5; const int mod = 1e9 + 7; int n; ll mp[30][30]; bool vis[30]; ll MIN; int v1[30]; int v2[30]; int prev1[30]; int prev2[30]; ll prenum = 0; ll C[35][35]; //C[n][m]就是C(n,m)
int tot; void init(int N) { for (int i = 0; i < N; i ++) { C[i][0] = C[i][i] = 1; for (int j = 1; j < i; j ++) { C[i][j] = C[i - 1][j] + C[i - 1][j - 1]; C[i][j] %= mod; } } } void dfs(int x, int deep) {//必須>=x開始,已經選了num我的
    if (deep == n) { tot--; if(tot<0){return;} int cnt1 = 0; int cnt2 = 0; for (int i = 1; i <= 2 * n; i++) { if (vis[i]) v1[++cnt1] = i; else v2[++cnt2] = i; } ll num = prenum; int pos = 1; for (int i = 1; i <= n; i++) { if (v1[i] != prev1[i]) { pos = i; break; } } for (int i = pos; i <= n; i++) { for (int j = 1; j <= n; j++) { num -= mp[prev1[i]][prev2[j]]; num -= mp[v1[i]][prev1[j]]; } for (int j = 1; j <= n; j++) { num += mp[v1[i]][v2[j]]; num += mp[v1[j]][prev1[i]]; } } MIN = max(MIN, num); for (int i = 1; i <= n; i++) { prev1[i] = v1[i]; prev2[i] = v2[i]; prenum = num; } return ; } for (int i = x + 1; i <= 2 * n; i++) { vis[i] = 1; dfs(i, deep + 1); if(tot<0){return;} vis[i] = 0; } } int main() { MIN = -1; init(30); scanf("%d", &n); tot=C[2*n][n]; tot/=2; for (int i = 1; i <= 2 * n; i++) { for (int j = 1; j <= 2 * n; j++) { scanf("%lld", &mp[i][j]); } } dfs(0, 0); printf("%lld\n", MIN); return 0; }
View Code
相關文章
相關標籤/搜索