Title: Link to original topic
Given n nodes, the right value between any two nodes, divide the n nodes into a A, a, two set, so that each node in the a set is combined with each node 22 in the B set (that is, there is | a|*| b| ) The sum of the weights is the largest.
Tag: A set: True B Set: false
Solution One: dfs+ pruning
#include <iostream>#include<cstring>using namespacestd;intN,ans;BOOL inch[ -];intgraph[ -][ -];voidDfsintIintcursum) { inch[i]=true; intmaxsum=cursum; for(intj=1; j<=n;j++){ if(!inch[j]) maxsum+=Graph[i][j]; Elsemaxsum-=Graph[i][j]; } if(Maxsum>ans) ans=maxsum; if(maxsum>cursum) {//Enumeration + recursion for(intj=i+1; j<=n;j++) DFS (j,maxsum); }//if the addition of Group A does not cause the maxsum to increase, it does not add in inch[i]=false; }intMain () {CIN>>N; memset (inch,0,sizeof(inch)); for(intI=1; i<=n;i++){ for(intj=1; j<=n;j++) Cin>>Graph[i][j]; } ans=0; DFS (1,0); cout<<ans<<Endl;}
Solution Two: randomization algorithm (good magic Idea)
#include <iostream>#include<cstdlib>using namespacestd; Const inttle= -;//time limit is 2000msintMain () {intn,m[ -][ -]; CIN>>N; for(intI=1; i<=n;i++){ for(intj=1; j<=n;j++) Cin>>M[i][j]; } /*Random Algorithm*/ BOOL inch[ -]={false}; intTime= -*tle;//make random times as large as possible, random results as close as possible to optimal solutions intmaxsum=0, cursum=0; while(time--){ intX=rand ()%n+1;//Range: 1~n inch[x]=!inch[x];//change the collection position where x is located for(intI=1; i<=n;i++){ if(inch[i]!=inch[x]) cursum+=M[i][x]; Elsecursum-=M[i][x]; } if(maxsum<cursum) maxsum=cursum; } cout<<maxsum<<Endl;}
PKU 2531 Network saboteur (dfs+ pruning | | randomization algorithm)