Codeforces 1042C (贪心+模拟)

题面

传送门

分析

思路简单,但代码较复杂的贪心
分类讨论:

  • 有0
    • 负数有奇数个:将绝对值最小(实际最大)的负数和0全部乘到一起,最后删掉0
    • 负数有偶数个:将0全部乘到一起,最后删掉0
  • 没有0
    • 负数有奇数个:将绝对值最小(实际最大)的负数删掉
    • 负数有偶数个:不删
      最后把剩下的数依次乘在一起即可

代码


#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#define maxn 200005
#define INF 0x7fffffff
using namespace std;
int n;
long long a[maxn];
struct oper {
	int type;
	int i;
	int j;
	oper() {

	}
	oper(int x,int y,int z) {
		type=x;
		i=y;
		j=z;
	}
	void print() {
		if(type==1) {
			printf("%d %d %d\n",type,i,j);
		} else {
			printf("%d %d\n",type,i);
		}
	}
};
vector<int>zeros;
vector<oper>res;
int main() {
	scanf("%d",&n);
	for(int i=1; i<=n; i++) {
		scanf("%I64d",&a[i]);
	}
	int cntneg=0,cnt0=0;
	long long maxneg=-INF;
	int del=0;
	for(int i=1; i<=n; i++) {
		if(a[i]==0) {
			zeros.push_back(i);//记录0的位置
			cnt0++;
		} else if(a[i]<0) {
			cntneg++;
			if(a[i]>maxneg) {
				maxneg=a[i];
				del=i;//记录最大的负数的位置
			}
		}
	}
	for(int i=0;i<cnt0-1;i++){
		res.push_back(oper(1,zeros[i],zeros[i+1]));//将0全部挪到一起
	}
	if(cntneg%2==1){//分类讨论
		if(cnt0!=0) res.push_back(oper(1,del,zeros[cnt0-1])),res.push_back(oper(2,zeros[cnt0-1],0));
		else res.push_back(oper(2,del,0));
	}else if(cnt0!=0) res.push_back(oper(2,zeros[cnt0-1],0));
	int last=0;
	for(int i=1; i<=n; i++) {
		if(a[i]!=0) {
			if(cntneg%2==1&&i==del) continue;
			else if(last==0) {
				last=i;
				continue;
			} else res.push_back(oper(1,last,i));
			last=i;
		}
	}
	for(int i=0; i<n-1; i++) {
		res[i].print();
	}
}

转载于:https://www.cnblogs.com/birchtree/p/9858035.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值