题意简述
给你一个(n)个节点的无向图(G={V,E})的邻接矩阵(g)和每个点的点权为(s_i),且(sum_{i=1}^n s_i = K),要你求出(mathrm{max} { sum_{u,v in E} s_u imes s_v})
做法
设两个不相邻的点(u),(v)的点权为(s_u)和(s_v),令(a_u = sum_{g[u][i]=1} s_i, a_v=sum_{g[v][i]=1} s_i),此时这对点((u,v))的贡献为(a_us_u+a_vs_v)。
- 不妨设(a_ugeq a_v),若(s_u=s_u+s_v,s_v=0),(ans)并不会变小。
所以最优解一定包含选取一个团(完全图)。对于一个(n)个点的完全图,这个完全图的答案为((frac {K}{n})^2 imes frac {n(n-1)}{2}),所以本题的答案为((frac {K}{tot})^2 imes frac {tot(tot-1)}{2}),其中(tot)为最大团的大小。
我们采用(Bron-Kerbosch)算法来求最大团,采用dfs剪枝的方法,时间复杂度(Oleft( 3^{n/3} ight))。
当然此题模拟退火也可以过,维护一个序列({c_n}),(s_i=frac {c_i}{sum_j c_j})。对于序列进行随机的$mod $固定值(如(100))意义下的加减,如果更优则转移。
代码实现
#include<bits/stdc++.h>
using namespace std;
#define re register int
#define ll long long
#define ak *
#define in inline
#define db double
in char getch()
{
static char buf[1<<12],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<12,stdin),p1==p2)?EOF:*p1++;
}
char qwq;
#define gc() getchar()
in int read()
{
re cz=0,ioi=1;qwq=gc();
while(qwq<'0'||qwq>'9') ioi=qwq=='-'?~ioi+1:1,qwq=gc();
while(qwq>='0'&&qwq<='9') cz=(cz<<3)+(cz<<1)+(qwq^48),qwq=gc();
return cz ak ioi;
}
const int N=45;
int n,k,g[N][N],ans,cnt[N],ch[N];
bool dfs(re u,re nw)
{
ch[nw]=u;
if(nw>ans) return ans=nw,true;
for(re i,v=u+1;v<=n;v++)
{
if(!g[u][v]||nw+cnt[v]<=ans) continue;
for(i=1;i<=nw;i++)
if(!g[ch[i]][v]) break;
if(i>nw&&dfs(v,nw+1)) return true;
}
return false;
}
in int bron_kerbosch()
{
for(re i=n;i;i--) dfs(i,1),cnt[i]=ans;
return ans;
}
int main()
{
n=read();k=read();
for(re i=1;i<=n;i++)
for(re j=1;j<=n;j++)
g[i][j]=read();
re cnt=bron_kerbosch();
if(!cnt) return puts("0"),0;
db per=1.0*k/cnt,tot=cnt*(cnt-1)/2.0;
printf("%.8lf",tot*pow(per,2));
return 0;
}