由一道基础算法题总结先++与后++的区别

题目链接:https://www.luogu.com.cn/problem/P1042

解题代码:

#include<iostream>
#include<string.h>
#include<cmath>

using namespace std;

int f[2]={11,21};
int a[25*2501+100];

int main()
{
	int tag=-1;
	char temp;
	while(1)
	{
		cin>>temp;
		if(temp=='E')
		{
			break;
		}
		else if(temp=='W')
		{
			a[++tag]=1;
		}
		else if(temp=='L')
		{
			a[++tag]=0;
		}
		//cout<<tag<<": "<<a[tag]<<endl;
	}
	for(int k=0;k<2;k++)
	{
		int w=0,l=0;
		for(int i=0;i<=tag;i++)
		{
			w+=a[i];
			l+=(1-a[i]);
			//cout<<i<<": "<<a[i]<<endl;
			if(max(w,l)>=f[k]&&abs(w-l)>=2)
			{
				cout<<w<<":"<<l<<endl;
				w=0;
				l=0;
			}
		}
		cout<<w<<":"<<l<<endl;
		cout<<"\n";
	}
}


if(temp==‘E’)
{
break;
}
else if(temp==‘W’)
{
a[++tag]=1;
}
else if(temp==‘L’)
{
a[++tag]=0;
}

这部分如果++tag改为tag++,就是wa。原因如下:
i++ 即后加加,原理是:先自增,然后返回自增之前的值
++i 即前加加,原理是:先自增,然后返回自增之后的值
由于此处最先定义tag=-1,那么要让数组序列从0开始,必须使用++tag;如果要使用tag++,那么最先定义时,要令tag=0。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值