Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 3105 Accepted Submission(s): 562
1 #include<cstdio> 2 #include<cstring> 3 #include<cstdlib> 4 #include<iostream> 5 #include<vector> 6 #include<algorithm> 7 //#pragma comment(linker, "/STACK:36777216,36777216") 8 using namespace std; 9 const int maxn=100005; 10 int father[maxn]; 11 bool vis[maxn]; 12 int indeg[maxn]; 13 int ans,n,m; 14 struct no 15 { 16 int next; 17 int sum; 18 }; 19 20 vector<no>tree[maxn]; 21 22 void init(int n){ 23 ans=-1; 24 tree[0].clear(); 25 for(int i=1;i<=n;i++){ 26 father[i]=i; 27 tree[i].clear(); 28 } 29 memset(vis,0,sizeof(vis)); 30 memset(indeg,0,sizeof(int)*(n+1)); 31 } 32 33 int find(int a) 34 { 35 while(a!=father[a]) 36 a=father[a]; 37 return a; 38 } 39 void dfs(int pos,int res) 40 { 41 ans=max(ans,res); 42 int len=tree[pos].size(); 43 for(int i=0;i<len;i++) 44 { 45 if(vis[tree[pos][i].next]==0) 46 { 47 vis[tree[pos][i].next]=1; 48 dfs(tree[pos][i].next,res+tree[pos][i].sum); 49 vis[tree[pos][i].next]=0; 50 } 51 } 52 } 53 54 int main() 55 { 56 int i,x,y,aa,bb,cc; 57 bool flag; 58 while(scanf("%d%d",&n,&m)!=EOF) 59 { 60 init(n); 61 flag=0; 62 for(i=1;i<=m;i++){ 63 scanf("%d%d%d",&aa,&bb,&cc); 64 indeg[aa]++; 65 indeg[bb]++; 66 tree[aa].push_back((no){bb,cc}); //无向图 67 tree[bb].push_back((no){aa,cc}); 68 if(!flag){ 69 x=find(aa); 70 y=find(bb); 71 if(x==y) flag=1; 72 else father[y]=x; 73 } 74 } 75 if(flag)printf("YES\n"); 76 else{ 77 //寻找端点 78 for(int i=1;i<=n;i++) { 79 if(indeg[i]==1) 80 tree[0].push_back((no){i,0}); //将多源汇集到一点 81 } 82 vis[0]=1; 83 dfs(0,0); 84 printf("%d\n",ans); 85 } 86 } 87 return 0; 88 }
hdu-----(4514)湫湫系列故事——设计风景线(树形DP+并查集)
原文:http://www.cnblogs.com/gongxijun/p/3973984.html