title Link:Sicily 1140
problem-solving ideas: greedy + deep Search
Quite a test of programming ability of a problem, a hand cheap card for several days, but it is a good question. The study is the use of greedy methods, as well as the ability to program-deep search. The greedy principle is to search from the minimum node (so that the minimum node is the root node), then for each node, search for the return node and the minimum node , according to test instructions comparison results, each greedy search after the deletion of the edge, and mark the entire sub-map, and then continue to search, Until all the people are divided into the estate.
Code:(may be redundant, but both are required for testing)
#include <bits/stdc++.h>#define INF 0x3f3f3f3fusing namespace Std;intNm, Cnt,start,end,ans,minx,Index_;intv[30005],sign[30005];vector<int>VEC[30005];p air<int,int> Dfs (int Index){intsum=1, len=VEC[Index].size (), tmp,tmp_min=Index; for(intI=0; i<len;i++) {if(VEC[Index][i]&&!sign[VEC[Index][i]]&&!v[VEC[Index][i]]) {v[VEC[Index][i]]=1; pair<int,int> New_pair=dfs (VEC[Index][i]);//cout<<VEC[Index][i]<<endl; Tmp=new_pair.first; sum+=tmp;inttmp1=cnt-tmp,tmp2=tmp;if(TMP1<=TMP2) {if(Tmp1>ans) {//cout<<"case1111111111"<<endl; ans=tmp1,minx=Index_; start=Index, end=VEC[Index][i]; }Else if(tmp1==ans&&minx>Index_) {//cout<<"case2222222222"<<endl; minx=Index_; start=Index, end=VEC[Index][i]; } }Else{if(Tmp2>ans) {//cout<<"case3333333333"<<endl; Ans=tmp2,minx=new_pair.second; start=Index, end=VEC[Index][i]; }Else if(Tmp2==ans&&minx>new_pair.second) {//cout<<"case4444444444"<<endl; Minx=new_pair.second; start=Index, end=VEC[Index][i]; }} tmp_min=min (Tmp_min,new_pair.second); }}//cout<<"DFS:"<<sum<<"Index:"<<Index<<"Minx:"<<minx<<endl;//cout<<start<<"&"<<end<<endl;returnMake_pair (sum,tmp_min);} void Remove (int Index){intlen=VEC[Index].size (); for(intI=0; i<len;i++)if(VEC[Index][i]&&!sign[VEC[Index][i]]) sign[VEC[Index][i]]=1, remove (VEC[Index][i]);}intMain () { while(~SCANF ("%d %d",&n,&m) {memset (sign,0, sizeof (sign)); MemsetVEC,0, sizeof (VEC));int x,y; for(intI=1; i<n;i++) {scanf ("%d %d",&x,&y);VEC[x].push_back (y);VEC[y].push_back (x); } cnt=n,start=-1, end=-1, sign[0]=1; for(intI=1;i<m; i++) {if(cnt==1) {printf("0");Continue; } memset (V,0, sizeof (v)); ans=0,Index_=-1, Minx=inf; for(intj=1; j<=n;j++)if(!sign[j]) {Index_=j; Break; } v[Index_]=1;intNum=dfs (Index_). Second;//cout<<i<<": "<<Index_<<endl;//cout<<"num:"<<num<<endl;//cout<<"!!!!!!!!!!!: "<<start<<"&"<<end<<endl;intlen=VEC[Start].size (); for(intI=0; i<len;i++)if(VEC[Start] [I]==end) {VEC[Start] [i]=0; Break; } len=VEC[End].size (); for(intI=0; i<len;i++)if(VEC[end] [I]==start) {VEC[end] [i]=0; Break; } sign[minx]=1; Remove (minx);printf("%d ", ans); Cnt-=ans; }printf("%d\ n", CNT); }return 0;}
Summary:
1, suddenly feel, the most difficult algorithm is greedy!
2, a retrospective example of the original is deep search?! (I've never known what backtracking is ...) )
Sicily 1140 (search)