printSTL

printПримеры решений задач

Бендер-парламентер (map, vector, partial_sort)
#include <map>
#include <algorithm>
#include <functional>
#include <string>
#include <cstdio>
#include <cctype>
#include <vector>
using namespace std;

typedef map<string,int> map1;
typedef map1::value_type mval1;
typedef const mval1 *pval1;
struct word_less: public binary_function<pval1, pval1, bool> {
  bool operator()(const pval1 v1, const pval1 v2)
  {  if(v1->second<v2->second) return false;
     if(v1->second>v2->second) return true;
     if(v1->first.length()>v2->first.length()) return true;
     if(v1->first.length()<v2->first.length()) return false;
     return v1->first<v2->first;
  }
};
struct copy_val: public unary_function<mval1,pval1> {
  pval1 operator()(const mval1 &v1)
  { return &v1;
  }
};

vector<pval1> words;
map1 m1;

int main()
{ int i,ch;
  string s;
  while((ch=getchar())!=EOF)
  { if(isalpha(ch))
      s+=tolower(ch);
    else
    { if(s.length()>0)
        ++m1[s];
      s.clear();
    }
  }
  transform(m1.begin(),m1.end(),back_inserter(words),copy_val());
  partial_sort(words.begin(),words.begin()+10,words.end(),word_less());
  for(i=0;i<10;i++)
    printf("%s\n",words[i]->first.c_str());
  return 0;
}

Collection of Postage Stamps (bitset)
#include <iostream>
#include <bitset>
using namespace std;
bitset<1000001> b;
int main()
{ int i,k,v;
  cin>>k;
  b.reset();
  b.set(0);
  for(i=0;i<k;i++)
  { cin>>v;
    b|=b<<v;
  }
  cout<<b.count()<<endl;
  return 0;
}

Сумма (vector, sort, upper_bound)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
  int n,k,s,a,i,maxlen,item,p,newlen;
  cin>>n>>k;
  vector<pair<int,int> > sum(n+1);
  sum[0]=make_pair(0,0);
  s=0;
  for(i=1;i<=n;++i)
  { cin>>a;
    s+=a;
    sum[i]=make_pair(s,i);
  }
  sort(sum.begin(),sum.end());
  item=maxlen=0;
  for(i=0;i<=n;i++)
  { if(i>0 && sum[i].first==sum[i-1].first) continue;
    p=upper_bound(sum.begin(),sum.end(),make_pair(sum[i].first+k,n+1))-sum.begin();
    if(p>0 && sum[p-1].first==sum[i].first+k &&
       (newlen=sum[p-1].second-sum[i].second)>0)
    { if(maxlen<newlen)
      { maxlen=newlen;
        item=sum[i].second+1;
      }
      else if(maxlen==newlen)
        item=min(item,sum[i].second+1);
    }
  } 
  cout<<item<<" "<<maxlen<<endl;
  return 0;
}
loading