PKU 2531 Network saboteur (dfs+ pruning | | randomization algorithm)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.