Let the total grains initially be $x$ kg.
Step 1: Sales to Customer 1
The shopkeeper sells half of the grains plus 3 kg to Customer 1. The remaining grains are:
\[\text{Remaining grains} = x - \left(\frac{x}{2} + 3\right).\]
Simplify:
\[\text{Remaining grains} = \frac{x}{2} - 3.\]
Step 2: Sales to Customer 2
The shopkeeper sells half of the remaining grains plus 3 kg to Customer 2. The remaining grains are:
\[\text{Remaining grains} = \left(\frac{x}{2} - 3\right) - \left(\frac{\frac{x}{2} - 3}{2} + 3\right).\]
Simplify step by step:
\[\text{Remaining grains} = \frac{x}{2} - 3 - \frac{\frac{x}{2} - 3}{2} - 3.\]
Combine terms:
\[\text{Remaining grains} = \frac{x}{2} - 3 - \frac{x}{4} + \frac{3}{2} - 3.\]
Simplify further:
\[\text{Remaining grains} = \frac{2x}{4} - \frac{x}{4} - 6 + \frac{3}{2}.\]
\[\text{Remaining grains} = \frac{x}{4} - \frac{9}{2}.\]
Step 3: Sales to Customer 3
When Customer 3 arrives, no grains are left:
\[\frac{x}{4} - \frac{9}{2} = 0.\]
Solve for $x$:
\[\frac{x}{4} = \frac{9}{2}.\]
Multiply through by 4:
\[x = 18.\]