ACM入出力テンプレート


ACMの場合、入出力のテンプレート:
1)第1行目が入力グループの個数であり、後に連続する動作が各グループの入力パラメータの場合:(例えばA+B)
3
10 11
1 2
4 5
第1行3は3組のテストデータを表し、第2行から第4行は異なるテストサンプルを表す:(C++)
#include
using namespace std;

int main()
{
      int n,a,b;
      cin>>n;
      while(n--!=0)
      {
               cin>>a>>b;
               cout<

Cバージョンの場合:
#include
using namespace std;

int main()
{
      int n,a,b;
      scanf("%d",&n);
      while(n--!=0)
      {
              scanf("%d%d",&a,&b);
              printf("%d
",a+b); } return 0; }

2)動作毎に各グループの入力パラメータの場合:(例えばA+B)
10 11
1 3
2 5
1行目から3行目にデータを入力します.
C++版:
#include
using namespace std;

int main()
{
      int a,b;
      while( cin>>a>>b)
      {
               cout<

C版:
#include
int main()
{
	int a,b; 
	while(scanf("%d%d",&a,&b) == 2) 
	{
		printf("%d
",a+b); } return 0; }

ここで、scanf("%d%d",&a,&b)==2は、指定されたフォーマット%d%dでデータが正しく読み込まれた個数を表す.
3)A+Bのような入力終了条件が後にある
各グループの入力は単独で1行を占め、入力が0 0の場合、入力は終了し、0のデータは処理されません.
たとえば、次のように入力します.
1 2
3 4
10 20
0 0
C++版:
#include
using namespace std;

int main()
{
      int a,b;
      while( cin>>a>>b && (a||b))
      {
               cout<

C版:
#include
int main()
{
	int a,b; 
	while(scanf("%d%d",&a,&b) == 2 && (a||b))
	{ 
		printf("%d
",a+b); } return 0; }

 
   
   4)       
  

: : A+B+C+...

: N, N

            0 , ,

3 1 2 4

1 23

5 1 3 5 7 9 

23

25

C++ :

#include
using namespace std;

int main()
{
	int n,t,s;
	while(cin>>n && n!=0)
	{
		s = 0;
		while(n--!=0)
		{
			cin>>t;
			s = s+ t;
		}
		cout<

C :
#include

int main()
{
	int n,t,s;
	while(scanf("%d",&n)== 1 && n!=0)
	{
		s = 0;
		while(n--!=0)
		{
			scanf("%d",&t);
			s = s+ t;
		}
		printf("%d
",s); } return 0; }