A Theory of Community Formation and Social Hierarchy