Tuesday, December 3, 2013

codechef "Sums in a Triangle" - SUMTRIAN guidance

codechef "Sums in a Triangle" - SUMTRIAN: http://www.codechef.com/problems/SUMTRIAN

Sums in a Triangle


All submissions for this problem are available.

Let's consider a triangle of numbers in which a number appears in the first line, two numbers appear in the second line, three in the third line, etc. Develop a program which will compute the largest of the sums of numbers that appear on the paths starting from the top towards the base, so that:
  • on each path the next number is located on the row below, more precisely either directly below or below and one place to the right;
  • the number of rows is strictly positive, but less than 100
  • all numbers are positive integers between O and 99.

Input

In the first line integer n - the number of test cases (equal to about 1000).
Then n test cases follow. Each test case starts with the number of lines which is followed by their content.

Output

For each test case write the determined value in a separate line.

Example

Input:
2
3
1
2 1
1 2 3
4 
1 
1 2 
4 1 2
2 3 1 1 

Output:
5
9


Warning: large Input/Output data, be careful with certain languages 

Author:admin
Tagsadmin
Date Added:1-12-2008
Time Limit:3 sec
Source Limit:5000 Bytes
Languages:ADA, ASM, BASH, BF, C, C99 strict, CAML, CLOJ, CLPS, CPP 4.3.2, CPP 4.8.1, CPP11, CS2, D, ERL, FORT, FS, GO, HASK, ICK, ICON, JAR, JAVA, JS, LISP clisp, LISP sbcl, LUA, NEM, NICE, NODEJS, PAS fpc, PAS gpc, PERL, PHP, PIKE, PRLG, PYTH, PYTH 3.1.2, RUBY, SCALA, SCM guile, SCM qobi, ST, TCL, TEXT, WSPC













and here is codechef "Sums in a Triangle" - SUMTRIAN guidance: http://discuss.codechef.com/questions/4557/need-guidance-in-sums-in-triangle-problem

It is said you need to start at the top of the triangle (where there is only one number) and keep moving to the number directly below or to the right until you reach the last row...
Take as an example the triangle:
1
1 2
9 2 3
If you want to maximize the sum by only moving right or down, is it clear to you that you should follow the path 1 -> 1 -> 9?
Note that 1 is not the maximum number you can choose on the 2nd row, but, it is the number that will "give you acess" to the number 9 on the third row, number which you will need to use if you want to reach the maximum sum...
This idea probably could lead us to use some sort of depth-first search and/or recursion... It turns out that for a triangle with as many rows as 100, there are 2^99 routes altogether... That would take you some billion years to check all of them if you could check one trillion of routes per second!!
So, we already know it would be good if we somehow knew in advance that we need to use number 9 on our solution without checking all possible routes... That can be done by using a bottom up approach instead of a top down one...
Let's list all the possible sums we can make with the last 2 rows (I am starting from right to left here):
using the 3 and 2 on last row we can have:
3+2 or 2+2 (summing them with the 2 on 2nd row, as it directly above or one place to the right);
Using the 9 and the 2 we get:
2+1 or 9+1
So, as you see two interesting things happened:
We used the same number (2) twice (one time for each of the 2 neighbouring numbers on the same row) and we also managed to obtain all 4 results:
5 or 4 for the 1st pair 3 or 10 for the 2nd pair
This suggests that as we are using some values to repeat calculations, we can use recursion with memoization to solve the problem fast, and that's what we will do up to a point, let's see:
We now know that the 2 maximum values we can obtain from the last rows are 5 and 10, so we replace these values on second row, and eliminate the third one completely, to get the new triangle:
1
10 5
From here, it's easy to see that the maximum sum is 11.
This approach works because we actually follow a down or to the right approach as required... Instead of starting at the top and waste all the time computing useless sums, by starting at the bottom and storing the maximum values we are "implicitly" removing lots of unnecessary values...
Hope I could help,
Bruno



and here is wiki info for the problem: http://www.codechef.com/wiki/recursion-sums-triangle

Recursion - Sums in a Triangle


An Introduction


Recursion, by definition, is a method of defining a function in a way such that the function being defined is applied within its own definition. A lot of problems in computer science can be broken down into smaller sub-problems. Most of these can have recursive solutions where the answer for each state is calculated from answers of smaller sub-states. Recursion, however, is very inefficient and most of the times, the answers for a particular state are calculated again and again. To overcome this limitation, a technique called memoization can be used. Memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously-processed inputs.

Thus, if the answers for each visited state are stored in a cache of sorts in the recursive solution, we can avoid re-calculating values we have already calculated.

We will see how to use these techniques to solve one of the easy level problems on Codechef.

Problem Tutorial - Sums in a Triangle

Sums in a Triangle http://www.codechef.com/problems/SUMTRIAN represents a broad range of problems that can be solved by using a recursive approach. As such, we will see one of the methods to solve it.

The problem asks one to take as input the number of test cases as the first input. Each test case consists of the number of rows 'n' and then 'n' lines follow containing each row.

The first row has 1 number, the second has 2 numbers, the 3rd has 3 numbers and so on. Now, We have to find a path from row 1 to row 'n' such that the cost of the path is maximized.

The cost of a path is the sum of all the numbers that make up the path. The additional constraint is that from a particular cell, we can only go to a cell in the next row directly beneath the cell or to the one situated to the right of the one beneath it. We start off in the topmost row and in its left most cell.

A very naive way to do this is to generate all paths, find the cost of the paths and choose the best one. Such an approach would time out because we can have a max of 100 rows.

Now, to model a problem in a recursive manner, we need subproblems which are similar to the problem to be solved. The prerequisites to modelling a recursive solution are

1. There should be subproblems

2. There should be terminating conditions called base conditions.

3. The sub-problem to be solved must be the same as the parent problem, but of a smaller magnitude or size.

4. There should be no cycles. One should not be able to reach a state, by starting off from it.
To solve this problem, we will try to see if it satisfies the prerequisites for a recursive problem.

1. First of all, we need to find subproblems. Consider a particular cell (i, j). From this cell, we can go either to cell (i + 1, j) or (i + 1, j + 1), where the first index represents the row and the second one represents the columns. Now, we need to maximize the sum for paths from cell (0, 0). Now, the maximum path value for cell (0, 0) will equal the value at cell(0, 0) + max(value of max path from cell(0, 1), value of max path from cell(1, 1)) Thus, we get the subproblems that we were looking for. The max path value at a particular cell equals the value at that cell + the max path values of cells reachable from it.

2. We can fix the terminating conditions as follows. The value of the max path if we reach a row beyond the 'n' rows specified is 0. This becomes our stopping condition for each path.

3. The subproblem to be solved is the same as the original problem. At each step we are making the size of the rows to be checked lesser and lesser and moving towards our base condition.

4. There are no cycles. There won't be a path such that we start from cell (i, j) and move on to some cells and reach cell(i, j) again. This can be seen by the fact that at each step, the row number keeps on increasing. It never decreases also, it never remains the same.

Thus, having modelled it as a recursive solution, we can create a recursive solution to the problem as follows.

Function solve(i, j)

if i is greater than 'n'

return 0

t1 equals solve(i + 1, j)

t2 equals solve(i + 1, j + 1)

t equals max(t1, t2) + value at cell(i, j)

return t

This simple recursive function will get us the answer for the path with the maximum cost. This will work for small values of 'n'. One thing that we notice is that in the given situation, we might end up calculating the value of the max path from a particular cell more than once. We can reach (3,2) in two ways. (1,1)>(2,1)>(3,2) and (1,1)>(2,2)>(3,2). The max value path from (3,2) will be calculated more than once even though we get the answer for it, the first time. A simple way to overcome this is to cache the value for the path from (3,2) the very first time we calculate it. A simple change to the function will give us the required effect.

Function solve(i, j)

if i is greater than 'n'

return 0

if i, j has been visited before

return cache(i, j)

t1 equals solve(i + 1, j)

t2 equals solve(i + 1, j + 1)

t equals max(t1, t2) + value at cell(i, j)

cache(i, j) equals t

return t

This technique is called recursion along with memoization. An analogous technique is Dynamic Programming which involves building the answer by using a bottom-up approach instead of the top-down approach used in the current method. A lot of problems which involve maximizing or minimizing values or which involve counting the number of patterns etc can be calculated using this technique.

Recursion Problems on CodeChef


The below mentioned problems can be solved once one understands the techniques mentioned in the tutorial.

http://www.codechef.com/problems/COINS

http://www.codechef.com/problems/MIXTURES

http://www.codechef.com/problems/MENU
Some standard recursive problems are Towers of HanoiFactorial,Compute Power Set.

Activities on Campus


Conduct a session on Campus:

Once a Chapter member solves one of the above mentioned practice problems he/she can conduct a session where the solution is explained to other participants/members on Campus. If required, this can be done with the help of a professor as well.

Other useful links



and here is my c++ triangle to the problem(it is TLE - time limit exceed on codechef): http://ideone.com/AhNRnV

#include <iostream>
using namespace std;

int main() {
 // your code goes here
 int a, b, arr[98][98], i, j, count=0, i_temp, j_temp, max, max1, max2;
 cin>>a;
 while(a--) {
  arr[98][98]=0;
  cin>>b;
  count=0;
  for(i=0; i<b; i++) {
   if(count<b) count++;
   for(j=0; j<count; j++) {
    cin>>arr[i][j];
   }
  }
  i_temp=i, j_temp=j;
  for(; i>0; i--) {
    j=j_temp;
    for(; j>0; j--) {
        max1=arr[i][j-1]+arr[i-1][j-1], max2=arr[i][j]+arr[i-1][j-1];
        if(max1>max2) max=max1; else max=max2;
        arr[i-1][j-1]=max;
    }
    j_temp=j_temp-1;
  }
  cout<<arr[0][0]<<endl;
  //arr[100][100]=0;
 }
 return 0;
}

my c++ solution to codechef "Turbo Sort" - TSORT problem

codechef "Turbo Sort" - TSORT problem: http://www.codechef.com/problems/TSORT/

Turbo Sort


All submissions for this problem are available.

Given the list of numbers, you are to sort them in non decreasing order.

Input

t – the number of numbers in list, then t lines follow [t <= 10^6].

Each line contains one integer: N [0 <= N <= 10^6]

Output

Output given numbers in non decreasing order.

Example

Input:
5
5
3
6
7
1
Output:
1
3
5
6
7

Author:admin
Tagsadmin
Date Added:1-12-2008
Time Limit:5 sec
Source Limit:50000 Bytes
Languages:ADA, ASM, BASH, BF, C, C99 strict, CAML, CLOJ, CLPS, CPP 4.3.2, CPP 4.8.1, CPP11, CS2, D, FORT, FS, GO, HASK, ICK, ICON, JAR, JAVA, JS, LISP clisp, LISP sbcl, LUA, NEM, NICE, NODEJS, PAS fpc, PAS gpc, PERL, PHP, PIKE, PRLG, PYTH, PYTH 3.1.2, RUBY, SCALA, SCM guile, SCM qobi, ST, TEXT, WSPC













and here is my c++ solution to codechef "Turbo Sort" - TSORT problem: http://ideone.com/HyUN3W

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
    int a, arr[1000001]={0}, b;
    scanf("%d", &a);
    while(a--) {
        scanf("%d", &b);
        arr[b]++;
    }
    for(int i=0; i<1000001; i++) {
        while(arr[i]>0) {
            printf("%d\n", i);
            arr[i]--;
        }
    }
    return 0;
}


and here is my solution VERSION 2: http://ideone.com/drtodU
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

const int lim=1e6+5;
int a[lim];

int main() {
    int t;
    scanf("%d", &t);
    for(int i=0; i<t; i++) scanf("%d", &a[i]);
    sort(a, a+t);
    for(int i=0; i<t; i++) printf("%d\n", a[i]);
    return 0;
}


NOTE: "scanf" & "printf" stuff is more quick than "cin" & "cout" in processing (or, at least, it seems so to me). the problem asks you to sort the given numbers in increasing order - "Given the list of numbers, you are to sort them in non decreasing order." means that. 

my c++ solution to codechef "Small Factorial" - FCTRL2 problem

 codechef "Small Factorial" - FCTRL2 problem: http://www.codechef.com/problems/FCTRL2

Small factorials


All submissions for this problem are available.

A tutorial for this problem is now available on our blog. Click here to read it.


You are asked to calculate factorials of some small positive integers.

Input


An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.

Output


For each integer n given at input, display a line with the value of n!

Example

Sample input:
4
1
2
5
3
Sample output:
1
2
120
6

Author:admin
Tagsadmin
Date Added:1-12-2008
Time Limit:1 sec
Source Limit:2000 Bytes
Languages:ADA, ASM, BASH, BF, C, C99 strict, CAML, CLOJ, CLPS, CPP 4.3.2, CPP 4.8.1, CPP11, CS2, D, ERL, FORT, FS, GO, HASK, ICK, ICON, JAR, JAVA, JS, LISP clisp, LISP sbcl, LUA, NEM, NICE, NODEJS, PAS fpc, PAS gpc, PERL, PERL6, PHP, PIKE, PRLG, PYTH, PYTH 3.1.2, RUBY, SCALA, SCM guile, SCM qobi, ST, TEXT, WSPC












Hello all !
The problem that we will be taking up is http://www.codechef.com/problems/FCTRL2/ :)
This problem basically asks you to calculate the factorial of a number up to 100. Now, I guess most of you know what a “factorial” is. For those who don’t, the factorial of a number N is 1*2*…*N. This problem would be very simple, had it not been for the maximum value of N. The structure of the problem is such that it asks the user to take the number of test cases as the first input. Then ‘t’ integers follow where ‘t’ is the number of test cases which was given as input previously.
For every integer here, we have to calculate the factorial. This is very simple in languages like python or java which have built-in support for big integer types. It proves to be a hassle for people using C / C++ or languages that do not have a built-in biginteger type. Let’s think about how we can store the the result.
Now, the maximum number that we can store in an unsigned 32 bit integer is 2 ^ 32 – 1 and in an unsigned 64 bit integer is 2 ^ 64 – 1. Something like 100!(‘!’ is the notation
for factorial) has over 150 decimal digits. The data types mentioned earlier can store numbers having at most 9 and 19 decimal digits respectively. So, we need to find a way to store the 150+ digits that we will get as the answer. The simplest data structure that we can use is an integer array of size of about 200 to be on the safe side.
In the simplest form, let us store one decimal digit per array index. So, if the number is say 120, then the array will have the numbers as follows:
Say a[200] is how we declare the array, then
a[0] = 0
a[1] = 2
a[2] = 1
The least significant digit is stored in the lowest index 0. The next one in index 1 and so on. Along with the array, we need an integer specifying the total number of digits in the array at the given moment. Let this number be ‘m‘. Initially, a[0] will be 1 and the value of ‘m‘ will be 1 specifying that we have just one digit in the array.
Let’s take a simple example first. Consider that the array has some value like 45 and we need to multiply it with a value 37. This can be done in the following way.
The array will be:
a[0] = 5
a[1] = 4
and the value of m will be 2 specifying that there are 2 digits in the array currently.
Now, to multiply this array with the value 37. We start off from the index 0 of the array to index 1. At every iteration, we calculate 37 * a[index]. We also maintain a temporary variable called temp which is initialized to 0. Now, at every step, we calculate x = a[index] * 37 + temp. The new value of a[index] will bex % 10 and the new value of temp will be temp / 10. We are simply carrying out multiplication the way it is carried out usually. So, for the current situation, the iterations will be something like this.
Initialize temp = 0
Iteration 1 : 
array = (5, 4)
temp = 0
index = 0, a[index] = 5
x = a[index] * 37 + temp = 5 * 37 + 0 = 185.
the new value of a[index] = 185 % 10 which is 5 and the new value of temp is 185 / 10 which is 18
Iteration 2 :
array : (5, 4)
temp = 18
index = 1, a[index] = 4
x = a[index] * 37 + temp = 4 * 37 + 18 = 166.
the new value of a[index] = 166 % 10 which is 6 and the new value of temp is 166 / 10 which is 16
We have finished 2 iterations and this is the value of ‘m‘, the array size at the moment. The required number of iterations is now over, but the value of temp is still greater than 0. This means that the current value of temp is to be incorporated into the array. For that, we keep appending the last digit of temp to the array and divide temp by 10 till temp becomes 0. So, we will get something like
Iteration 1 : 
temp = 16 , array = (5, 6)
So, we add 16 % 10 to the array so that the array becomes (5, 6, 6) and we divide temp by 10 so that temp becomes 1. We update the value of ‘m’ to m + 1 that is m = 3
Iteration 2 :
temp = 1, array = (5, 6, 6)
Now, we add 1 % 10 to the array so the array becomes (5, 6, 6, 1) and we divide temp by 10 so that temp becomes 0. We update the value of ‘m’ to m + 1 that is m = 4
The value of temp is now 0 and our multiplication is now over. The final array we get is (5, 6, 6, 1)
Voila, we have the answer to 45 * 37 in our array with the Least significant digit in the 0th position. :)
For finding the factorial, we need to carry out this exact multiplication operation at every step as we loop from 1 to N. At the end of the Nth iteration, our array will contain
the answer and the value of m will be the number of digits in the answer. We can then just print the array from the Most significant digit to the least for the answer.
The basic flow of the program will be as below :
Start
Take in the number of test cases
While there is a test case remaining to be handled
    Take in the number whose factorial is to be found, let it be N
    Initialize the array's 0th index to 1 and m to 1
    Initialize i to 1
    While i is less than or equal to N
        Carry out multiplication of the array with 'i' as shown above.
    Print the contents of the array starting from the most significant digit and ending with the least significant digit.
Stop
Certain improvements can be made to the above mentioned method. We are storing only one digit per array index, We can store more than 1 digit per index so that the number of computations are reduced. The method to do that is the same as above. We leave it to the reader as an exercise :)



and here is my c++ solution to codechef "Small Factorial" - FCTRL2 problem: http://ideone.com/B3pFyv

#include <iostream>
using namespace std;

int main() {
// your code goes here
int a;
cin>>a;
while(a--) {
int b, arr[200]={0};
cin>>b;
arr[0]=1;
int i=1, m=1, index=0, temp=0, x;
while(i<=b) {
int k=m;
index=0;
while(k--) {
x=arr[index]*i+temp;
arr[index]=x%10, temp=x/10, index++;
}
while(temp!=0) {
arr[index]=temp%10;
temp=temp/10;
index++, m++;
}
i++;
}
while(m--) cout<<arr[m];
cout<<endl;
}
return 0;
}

Monday, December 2, 2013

c++ solution to codechef "Holes in the text" problem

problem link: http://www.codechef.com/problems/HOLES/
i suggest you to look at: http://discuss.codechef.com/questions/4184/holes-editorial

Holes in the text

All submissions for this problem are available.

Chef wrote some text on a piece of paper and now he wants to know how many holes are in the text. What is a hole? If you think of the paper as the plane and a letter as a curve on the plane, then each letter divides the plane into regions. For example letters "A", "D", "O", "P", "R" divide the plane into two regions so we say these letters each have one hole. Similarly, letter "B" has two holes and letters such as "C", "E", "F", "K" have no holes. We say that the number of holes in the text is equal to the total number of holes in the letters of the text. Help Chef to determine how many holes are in the text.

Input

The first line contains a single integer T <= 40, the number of test cases. T test cases follow. The only line of each test case contains a non-empty text composed only of uppercase letters of English alphabet. The length of the text is less then 100. There are no any spaces in the input.

Output

For each test case, output a single line containing the number of holes in the corresponding text.

Example

Input:
2
CODECHEF
DRINKEATCODE

Output:
2
5

my c++ solution to codechef "Holes in the text" problem: http://ideone.com/Jj4OLR

#include <iostream>
#include <cstring>
using namespace std;

int main() {
 // your code goes here
 int a;
 char str[100];
 cin>>a;
 while (a--) {
  cin>>str;
  int x=0;
  for(int i=0; i<strlen(str); i++) {
   if (str[i]=='A') x=x+1;
   else if (str[i]=='D') x=x+1;
   else if (str[i]=='O') x=x+1;
   else if (str[i]=='P') x=x+1;
   else if (str[i]=='Q') x=x+1;
   else if (str[i]=='R') x=x+1;
   else if (str[i]=='B') x=x+2;
   else x=x+0;
  }
  cout<<x<<endl;
 }
 return 0;
}

Sunday, November 3, 2013

codechef FCTRL - Factorial c++ solution

codechef FCTRL - Factorial problem: http://www.codechef.com/problems/FCTRL

Factorial

All submissions for this problem are available.


The most important part of a GSM network is so called
Base Transceiver Station (BTS). These transceivers form the
areas called cells (this term gave the name to the cellular phone)
and every phone connects to the BTS with the strongest signal (in
a little simplified view). Of course, BTSes need some attention and
technicians need to check their function periodically.


The technicians faced a very interesting problem recently. Given a set of
BTSes to visit, they needed to find the shortest path to visit all of the
given points and return back to the central company building. Programmers
have spent several months studying this problem but with no results. They
were unable to find the solution fast enough. After a long time, one of the
programmers found this problem in a conference article. Unfortunately, he
found that the problem is so called "Traveling Salesman Problem" and it is
very hard to solve. If we have N BTSes to be visited, we can visit them in
any order, giving us N! possibilities to examine. The function expressing
that number is called factorial and can be computed as a product
1.2.3.4....N. The number is very high even for a relatively small N.


The programmers understood they had no chance to solve the problem. But
because they have already received the research grant from the government,
they needed to continue with their studies and produce at least some
results. So they started to study behavior of the factorial function.


For example, they defined the function Z. For any positive integer N,
Z(N) is the number of zeros at the end of the decimal form of number
N!. They noticed that this function never decreases. If we have two numbers
N1<N2, then
Z(N1) <= Z(N2). It is because we can never "lose" any
trailing zero by multiplying by any positive number. We can only get new
and new zeros. The function Z is very interesting, so we need a computer
program that can determine its value efficiently.

Input


There is a single positive integer T on the first line of input (equal to about 100000). It stands
for the number of numbers to follow. Then there are T lines, each containing
exactly one positive integer number N,
1 <= N <= 1000000000.

Output


For every number N, output a single line containing the single non-negative
integer Z(N).

Example

Sample Input:
6
3
60
100
1024
23456
8735373
Sample Output:
0
14
24
253
5861
2183837



and here is my c++ solution to codechef FCTRL - Factorial : http://ideone.com/QmVocm

#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;

int main() {
 // your code goes here
 int a, b, c;
 cin>>a;
 while(a--) {
  cin>>b;
  c=0;
  for (int i=1; pow(5, i)<=b; i++) {
   c=c+b/pow(5, i);
   //i++;
  }
  cout<<c<<endl;
 }
 return 0;
}

codechef INTEST - Enormous Input Test c++ solution

codechef INTEST - Enormous Input Test problem: http://www.codechef.com/problems/INTEST

All submissions for this problem are available.

The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.

Input

The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 109, each.

Output

Write a single integer to output, denoting how many integers ti are divisible by k.

Example

Input:
7 3
1
51
966369
7
9
999996
11

Output:
4


and here is my codechef INTEST - Enormous Input Test c++ solution: http://ideone.com/T05cEX

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
 // your code goes here
 int a, b, c, d=0;
 scanf("%d %d", &a, &b);
 while (a--) {
  scanf("%d", &c);
  if(c%b==0) d++;
 }
 printf("%d", d);
 return 0;
}

Note: I was looking for "buffer c++" all over the web, but I could not get over it. c++ "cin" and "cout" makes some WA. so, instead, just try c "scanf" and "printf", that would be helpful, and easy to understand. "buffer" is extremely difficult to me to understand the code. good luck guys.

Saturday, November 2, 2013

buffer c++, Unix and gnu gcc buffering

Here buffering is explained: http://gcc.gnu.org/onlinedocs/libstdc++/manual/streambufs.html

Stream Buffers

Derived streambuf Classes


Creating your own stream buffers for I/O can be remarkably easy. If you are interested in doing so, we highly recommend two very excellent books: Standard C++ IOStreams and Locales by Langer and Kreft, ISBN 0-201-18395-1, and The C++ Standard Library by Nicolai Josuttis, ISBN 0-201-37926-0. Both are published by Addison-Wesley, who isn't paying us a cent for saying that, honest.
Here is a simple example, io/outbuf1, from the Josuttis text. It transforms everything sent through it to uppercase. This version assumes many things about the nature of the character type being used (for more information, read the books or the newsgroups):
    #include <iostream>
    #include <streambuf>
    #include <locale>
    #include <cstdio>

    class outbuf : public std::streambuf
    {
      protected:
 /* central output function
  * - print characters in uppercase mode
  */
 virtual int_type overflow (int_type c) {
     if (c != EOF) {
  // convert lowercase to uppercase
  c = std::toupper(static_cast<char>(c),getloc());

  // and write the character to the standard output
  if (putchar(c) == EOF) {
      return EOF;
  }
     }
     return c;
 }
    };

    int main()
    {
 // create special output buffer
 outbuf ob;
 // initialize output stream with that output buffer
 std::ostream out(&ob);

 out << "31 hexadecimal: "
     << std::hex << 31 << std::endl;
 return 0;
    }
   
Try it yourself! More examples can be found in 3.1.x code, in include/ext/*_filebuf.h, and in this article by James Kanze: Filtering Streambufs.

Buffering

First, are you sure that you understand buffering? Particularly the fact that C++ may not, in fact, have anything to do with it?
The rules for buffering can be a little odd, but they aren't any different from those of C. (Maybe that's why they can be a bit odd.) Many people think that writing a newline to an output stream automatically flushes the output buffer. This is true only when the output stream is, in fact, a terminal and not a file or some other device -- and that may not even be true since C++ says nothing about files nor terminals. All of that is system-dependent. (The "newline-buffer-flushing only occurring on terminals" thing is mostly true on Unix systems, though.)
Some people also believe that sending endl down an output stream only writes a newline. This is incorrect; after a newline is written, the buffer is also flushed. Perhaps this is the effect you want when writing to a screen -- get the text out as soon as possible, etc -- but the buffering is largely wasted when doing this to a file:
   output << "a line of text" << endl;
   output << some_data_variable << endl;
   output << "another line of text" << endl; 
The proper thing to do in this case to just write the data out and let the libraries and the system worry about the buffering. If you need a newline, just write a newline:
   output << "a line of text\n"
   << some_data_variable << '\n'
   << "another line of text\n"; 
I have also joined the output statements into a single statement. You could make the code prettier by moving the single newline to the start of the quoted text on the last line, for example.
If you do need to flush the buffer above, you can send an endl if you also need a newline, or just flush the buffer yourself:
   output << ...... << flush;    // can use std::flush manipulator
   output.flush();               // or call a member fn 
On the other hand, there are times when writing to a file should be like writing to standard error; no buffering should be done because the data needs to appear quickly (a prime example is a log file for security-related information). The way to do this is just to turn off the buffering before any I/O operations at all have been done (note that opening counts as an I/O operation):
   std::ofstream    os;
   std::ifstream    is;
   int   i;

   os.rdbuf()->pubsetbuf(0,0);
   is.rdbuf()->pubsetbuf(0,0);

   os.open("/foo/bar/baz");
   is.open("/qux/quux/quuux");
   ...
   os << "this data is written immediately\n";
   is >> i;   // and this will probably cause a disk read 
Since all aspects of buffering are handled by a streambuf-derived member, it is necessary to get at that member with rdbuf(). Then the public version of setbuf can be called. The arguments are the same as those for the Standard C I/O Library function (a buffer area followed by its size).
A great deal of this is implementation-dependent. For example, streambuf does not specify any actions for its own setbuf()-ish functions; the classes derived from streambuf each define behavior that "makes sense" for that class: an argument of (0,0) turns off buffering for filebuf but does nothing at all for its siblings stringbuf and strstreambuf, and specifying anything other than (0,0) has varying effects. User-defined classes derived from streambuf can do whatever they want. (For filebuf and arguments for (p,s) other than zeros, libstdc++ does what you'd expect: the first s bytes of p are used as a buffer, which you must allocate and deallocate.)
A last reminder: there are usually more buffers involved than just those at the language/library level. Kernel buffers, disk buffers, and the like will also have an effect. Inspecting and changing those are system-dependent.