Test instructions
- An adjacency matrix of the graph is given, and the graph is divided into two regions, and the maximum distance between the nodes in different regions is obtained.
Method:
- Use DFS to enumerate which areas each point is in.
- I started here with each enumeration to the tree's leaf node, calculating the distance, so that each calculation is < Span class= "Mrow" id= "mathjax-span-197" > n 2 Span style= "Display:inline-block; width:0px; Height:2.349em; " > , changing the distance after each change is reduced by 5 times times, because the calculation of each leaf node is less than N.
- Here's the second code, the list of parameters in the DFS function has a sum to maintain the distance
Enumeration to the leaf node recalculation code: (1766MS)
#include <set>#include <stack>#include <queue>#include <vector>#include <cstdio>#include <map>#include <cstring>#include <cstdlib>#include <iostream>#include <algorithm>#define LL Long Long intusing namespace STD;Const intm= in, inf=0x3fffffff;intDiagram[m][m],n,str[m],ans=-inf;intCalvoid){intsum=0; for(intI=1; I <= n;i++) {if(Str[i]) for(intj=1; J <= n;j++) {if(!str[j]) {SUM+=DIAGRAM[I][J]; } } }returnsum;}voidDfsintx) {if(x > N) {intX=cal ();if(x > Ans) ans=x;return; } for(intI=0; I <2; i++) {str[x]=i; DFS (x+1); Str[x]=!i; }return;}intMainvoid){ while(~scanf("%d", &n)) {ans=-inf; for(intI=1; I <= n;i++) { for(intj=1; J <= n;j++) {scanf("%d", &diagram[i][j]); }} DFS (1);printf("%d\n", ans); }return 0;}
Change the distance code for each change: (297MS)
#include <set>#include <stack>#include <queue>#include <vector>#include <cstdio>#include <map>#include <cstring>#include <cstdlib>#include <iostream>#include <algorithm>#define LL Long Long intusing namespace STD;Const intm= in, inf=0x3fffffff;intDiagram[m][m],n,str[m],ans=-inf;voidDfsintXintSUM) {if(x > N) {if(Sum > ans) ans = sum;return; } for(intI=0; I <2; i++) {inttemp =0, key = Str[x];if(str[x]! = i) {Str[x] = i; for(intj =1; J <= N; J + +) {if(J! = x && Str[j] = = i) temp-= diagram[j][x];Else if(Str[j]! = i) temp + = diagram[j][x]; }} DFS (x +1, sum + temp); STR[X] = key; }return;}intMainvoid){ while(~scanf("%d", &n)) {ans=-inf; for(intI=1; I <= n;i++) { for(intj=1; J <= n;j++) {scanf("%d", &diagram[i][j]); }} DFS (1,0);printf("%d\n", ans); }return 0;}
HDU 2531 DFS non-map partition