您的位置:首页 > 编程语言 > Java开发

第七届蓝桥杯JavaB组-压缩变换

2018-03-28 15:10 176 查看
压缩变换

小明最近在研究压缩算法。
他知道,压缩的时候如果能够使得数值很小,就能通过熵编码得到较高的压缩比。
然而,要使数值很小是一个挑战。
最近,小明需要压缩一些正整数的序列,这些序列的特点是,后面出现的数字很大可能是刚出现过不久的数字。
对于这种特殊的序列,小明准备对序列做一个变换来减小数字的值。
变换的过程如下:
从左到右枚举序列,
1、每枚举到一个数字,如果这个数字没有出现过,刚将数字变换成它的相反数
2、如果数字出现过,则看它在原序列中最后的一次出现后面(且在当前数前面)出现了几种数字,
用这个种类数替换原来的数字。

比如,序列(a1, a2, a3, a4, a5)=(1, 2, 2, 1, 2)在变换过程为:
a1: 1未出现过,所以a1变为-1;
a2: 2未出现过,所以a2变为-2;
a3: 2出现过,最后一次为原序列的a2,在a2后、a3前有0种数字,所以a3变为0;
a4: 1出现过,最后一次为原序列的a1,在a1后、a4前有1种数字,所以a4变为1;
a5: 2出现过,最后一次为原序列的a3,在a3后、a5前有1种数字,所以a5变为1。
现在,给出原序列,请问,按这种变换规则变换后的序列是什么。

输入格式:
输入第一行包含一个整数n,表示序列的长度。
第二行包含n个正整数,表示输入序列。

输出格式:
输出一行,包含n个数,表示变换后的序列。

例如,输入:
5
1 2 2 1 2

程序应该输出:
-1 -2 0 1 1

再例如,输入:
12
1 1 2 3 2 3 1 2 2 2 3 1

程序应该输出:
-1 0 -2 -3 1 1 2 2 0 0 2 2

数据规模与约定
对于30%的数据,n<=1000;
对于50%的数据,n<=30000;
对于100%的数据,1 <=n<=100000,1<=ai<=10^9
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗  < 3000ms
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main{

public static int judgeFirstAppearance(int[] arr, int pos) {
for(int i = pos - 1; i >= 0; --i) if(arr[i] == arr[pos]) return i;
return -1;
}

public static int calculateKinds(int[] arr, int lastPos, int thisPos) {
int[] tempArr = new int[thisPos - lastPos - 1];
int lim = 0, cnt = 0;
//把检测区间的数据放到另外一个数组中
for(; lim + lastPos + 1 < thisPos; ++lim) tempArr[lim] = arr[lim + lastPos + 1];

/**
* for循环一个一个比较,把第一次出现的直接cnt++,然后再遍历该区间,把和当前元素相同的都置位-1;
* */
for(int i = 0; i < lim; ++i) {
if(tempArr[i] == -1) continue;
++cnt;
for(int j = i + 1; j < lim; ++j)
if(tempArr[j] == tempArr[i]) { tempArr[j] = -1; }
}
return cnt;
}

public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.valueOf(in.readLine());
String[] str_arr = in.readLine().split(" ");
in.close();
int[] arr = new int[str_arr.length];
int[] ans = new int[str_arr.length];
for(int i = 0; i < str_arr.length; ++i) arr[i] = Integer.valueOf(str_arr[i]);

/**
* 我的方法比较笨,完全根据题目的要求来写的!
* 数据量太大可能就是超时!
* 看到这篇博客的朋友,有想法的话可以在评论区留言,有错误的话,还望各位不吝赐教!THANKS
* */
for(int i = 0; i < arr.length; ++i) {
int lastPos = judgeFirstAppearance(arr, i);
if(-1 == lastPos) { ans[i] = arr[i]*-1; continue; }
ans[i] = calculateKinds(arr, lastPos, i);
}

boolean flag = true;
for(int item: ans) if(flag){ System.out.print(item); flag = false; } else System.out.print(" " + item);
System.out.println();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息