Official

C - Remembering the Days Editorial by en_translator


This problem can be solved with a DFS (Depth-First Search).

Maintain the current town, already visited towns, and the total length of the roads traversed so far, while advancing to an unvisited town.

The complexity is \(O(N N!)\), which is fast enough.

Note that it is common in competitive programming to use global variables as the state of DFS instead of passing everything as arguments of DFS, in order to simplify the implementation.

Sample code (Python)

N,M=map(int,input().split())
E=[[0]*(N+1) for _ in range(N+1)]
for _ in range(M):
  a,b,c=map(int,input().split())
  E[a][b]=c
  E[b][a]=c

ans=0
used=[False]*(N+1)

def dfs(v,s):
  global ans
  used[v]=True
  if s>ans: ans=s
  for i in range(1,N+1):
    if not used[i] and E[v][i]:
      dfs(i,s+E[v][i])
  used[v]=False

for i in range(1,N+1):
  dfs(i,0)

print(ans)

Sample code (C)

#include<stdio.h>
#define max(p,q)((p)>(q)?(p):(q))

int n,m;
int e[11][11];
int used[11];
int ans;
void dfs(int v,int sum){
	used[v]=1;
	ans=max(ans,sum);
	for(int i=1;i<=n;i++)if(!used[i]&&e[v][i])dfs(i,sum+e[v][i]);
	used[v]=0;
}

int main(){
	scanf("%d%d",&n,&m);
	for(int i=0;i<m;i++){
		int a,b,c;
		scanf("%d%d%d",&a,&b,&c);
		e[a][b]=e[b][a]=c;
	}
	for(int i=1;i<=n;i++)dfs(i,0);
	printf("%d\n",ans);
}

posted:
last update: