Advertisement
Guest User

Untitled

a guest
Jan 19th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include <fstream>
  2. #include <algorithm>
  3. using namespace std;
  4. ifstream fi("marmot.in");
  5. ofstream fo("marmot.out");
  6. const int NMAX=1e6+5,INF=1e9;
  7. int n,s[NMAX],sum;
  8. pair <int,int> m[NMAX],in[NMAX];
  9. void structure(int nr)
  10. {
  11.     if(in[-nr].first<0)
  12.     {
  13.         fo<<"{";
  14.         structure(in[-nr].first);
  15.         fo<<"}";
  16.     }
  17.     else fo<<"("<<s[in[-nr].first]<<")";
  18.     if(nr==-n+1)
  19.         fo<<"-root-";
  20.     else fo<<"-i-";
  21.     if(in[-nr].second<0)
  22.     {
  23.         fo<<"{";
  24.         structure(in[-nr].second);
  25.         fo<<"}";
  26.     }
  27.     else fo<<"("<<s[in[-nr].second]<<")";
  28. }
  29. int main()
  30. {
  31.     ///n=number of marmots
  32.     fi>>n;
  33.     for(int i=1;i<=n;i++)
  34.     {
  35.         fi>>m[i].first;///m[i].first=number of awakenings for marmot i
  36.         m[i].second=i;///m[i].second=the indice before sorting of the marmot i
  37.         ///(we need this number for the structure)
  38.         s[i]=m[i].first;
  39.     }
  40.     sort(m+1,m+n+1);
  41.     for(int i=1;i<n;i++)
  42.     {
  43.         sum+=m[1].first+m[2].first;
  44.         m[1].first=m[1].first+m[2].first; /// we give m[1] the value of the new intersection created
  45.         in[i]={m[1].second,m[2].second};
  46.         m[1].second=-i;
  47.         m[2].first=INF;///we give m[2] a big value in order to avoid using it again
  48.         sort(m+1,m+n+1);
  49.     }///we repeat this process n-1 times, because in the end we need to have one intersection left, which is the root
  50.     fo<<"minimal sum is "<<sum<<"\n";///sum=answer to our problem, the sum of weights
  51.     ///In this algorithm we find the minimal sum in complexity O(N^2*log2N)
  52.     structure(-(n-1));
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement