Sicily 1024 Magic Island

找出一个无向图中的最长路,直接DFS。

#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
struct edge{
       int b,e,d;
       edge( int aa,int bb, int cc ) {
             b=aa;
             e=bb;
             d=cc;
       }
};
vector<edge> data[10010];
int n;
int ma;
void df_search( int city, int length ) {
     int i,end,begin,j;
     if ( length > ma )
     ma=length;
     for ( i=0;i<data[city].size(); i++ ) {
         if ( data[city][i].d>0 ) {
              length += data[city][i].d;
              data[city][i].d=-data[city][i].d;
              end=city;
              begin=data[city][i].e;
              for ( j=0;j<data[begin].size();j++ ) {
                  if ( data[begin][j].e==end ) {
                       data[begin][j].d=-data[begin][j].d;
                       break;
                  }
              }
              df_search( begin, length );
              length+=data[city][i].d;
              data[city][i].d=-data[city][i].d;
              for ( j=0;j<data[begin].size();j++ ) {
                  if ( data[begin][j].e==end ) {
                       data[begin][j].d=-data[begin][j].d;                      
                       break;
                  }
              }
         }
     }
}              
int main()
{
    int k,i,j,d,length,ctr;
    
    while ( scanf( "%d",&n )!= EOF ) {
          scanf( "%d",&k );
          for ( ctr=1;ctr<n;ctr++ ) {
              scanf( "%d%d%d",&i,&j,&d );
              data[i].push_back( edge(i,j,d) );
              data[j].push_back( edge(j,i,d) );
          }
          ma=0;
          length=0;
          df_search( k, length );
          printf("%d\n", ma );
          for ( i=0;i<=n;i++)
          data[i].clear();
    }
    return 0;
}

你可能感兴趣的:(search)