ZZU15级软工最后一次算法作业

来源:互联网 发布:祥南行书体 mac 编辑:程序博客网 时间:2024/06/05 19:49

由于高考改卷要占用我们学校的机房,所以我们的上机课就停了。助教让我们在POj上做 poj1521   poj1751   poj3032 (这都是超链接)这三道题。然而,对于多数不搞ACM的同学来说,刚做OJ试题,有些难度。确实有点难为大家了。

对于多数萌新来时,第一次看见英文题目描述,可能已经开始瑟瑟发抖了,吐舌头。不过没关系,这很正常。我刚开始做题时,a + b就通过不了。

对于ACM或OI……(二次编辑,同学说我博客措辞太那啥了,不符合我的风格,此处就删除几十字)。


题解(先易后难):

这是一道游戏模拟题。大概意思:

有一摞牌

1,把1张牌放到这摞牌底,然后牌顶是1,把这张1放到桌子上。

2,把2张牌放到这摞牌底,然后牌顶是2,把这张2放到桌子上。

……

n,把(n mod 剩余牌总张数)张牌放到这摞牌底,然后牌顶是n,把这张n放到桌子上。

模拟题,主要考察算法实现能力,不用怎么动脑子。(为什么僵尸吃了人的脑子,那人还能活着?因为有的人没有脑子,不也很快乐吗。)纯C语言实现(C99标准)

#include <stdio.h> #define N 112int main(){int T;scanf("%d", &T);while (T-- > 0) {int n;scanf("%d", &n);int ary[N] = { 0 };int cur = 0, i;for (i = 1; i <= n; ++i) {int k = 0;while (k != i) {if (ary[cur] == 0) {k++;}cur = (cur + 1) % n;}while (ary[cur] != 0) {cur = (cur + 1) % n;}ary[cur] = i;}printf("%d", ary[0]);for (i = 1; i < n; ++i) {printf(" %d", ary[i]);}puts("");}return 0;}

优化一下(若C报编译错,用C++)

#include <stdio.h>     #define N 112    int main()    {         int T;        scanf("%d", &T);        while (T-- > 0) {            int n;            scanf("%d", &n);            int ary[N] = { 0 };           int cur = 0, i, left = n; //left 剩余卡片数,初始剩余n张           for (i = 1; i <= n; ++i) {                int k = -1, j = i % left;               while (1) {                   if (ary[cur] == 0 && ++k == j) { //寻找下一个还在手中的卡片              break;                  }                   cur = (cur + 1) % n;               }               ary[cur] = i;  //拿出一张卡片               left--; //剩余卡片数减1           }            printf("%d", ary[0]);            for (i = 1; i < n; ++i) {                printf(" %d", ary[i]);            }            puts("");        }            return 0;    }    



再说一个比较好玩的解法

#include <stdio.h> int main(){char *p[13] = {"1", "2 1", "3 1 2", "2 1 4 3", "3 1 4 5 2", "4 1 6 3 2 5", "5 1 3 4 2 6 7" , "3 1 7 5 2 6 8 4", "7 1 8 6 2 9 4 5 3", "9 1 8 5 2 4 7 6 3 10", "5 1 6 4 2 10 11 7 3 8 9" , "7 1 4 9 2 11 10 8 3 6 5 12", "4 1 13 11 2 10 6 7 3 5 12 9 8"};int T;scanf("%d", &T);while(T--) {int n;scanf("%d", &n);if (0 < n && n < 14)puts(p[n - 1]);}return 0;}


1751这题考查最小生成树MST,实现算法有prim(O(nlgn)), 克鲁斯卡尔算法 O(elge)
题意:有n个城市,编号1到n,给出这n个城市的坐标。其中m个城市间已经有路,问在连接哪几个城市,可是使任意两座城市间有路。
下面是我用prim 算法(参见我们上学期数据结构是如何实现的)实现的,纯C(99)。
注:最小生成树很可能不唯一,只要输出其中一种情况就好。(最小生成树的长度唯一)

#include <stdio.h> #define INF 0x7f7f7f7f#define maxn 755int n;int x[maxn], y[maxn], pre[maxn];double pic[maxn][maxn]; //1:n void MST(double matrix[][maxn], int n) {double lowCost[maxn];int i, j;for (i = 1; i <= n; ++i) {lowCost[i] = matrix[1][i];pre[i] = 1;}lowCost[1] = -1;for (i = 1; i < n; ++i) { //循环n-1次 double minW = INF;int u = -1;for (j = 1; j <= n; ++j) {if (lowCost[j] != -1 && minW > lowCost[j]) {minW = lowCost[j];u = j;}}if (matrix[pre[u]][u]) {printf("%d %d\n", pre[u], u);}lowCost[u] = -1;for (j = 1; j <= n; ++j) {if (lowCost[j] > matrix[u][j]) {lowCost[j] = matrix[u][j];pre[j] = u;}}}}int main(){while(~scanf("%d", &n)) {int i, j, m, tmpx, tmpy;for (i = 1; i <= n; ++i) {scanf("%d%d", x + i, y + i);}scanf("%d", &m);for (i = 1; i <= n; ++i) {for (j = 1; j <= i; ++j) {pic[i][j] = pic[j][i] = (x[j] - x[i])*(x[j] - x[i]) + (y[j] - y[i])*(y[j] - y[i]);}} for (i = 0; i < m; ++i) {scanf("%d%d", &tmpx, &tmpy);pic[tmpx][tmpy] = pic[tmpy][tmpx] = 0.0;}MST(pic, n);}return 0;}


1521考察哈夫曼编码。
给出一个字符串(END结束输入,不做处理),求其一般ASCII编码长度,Huffman编码长度,二者的倍数(压缩比)。由于这题我用了优先队列,所以就不用纯C了,用C++或者Java。
AAAAABCD
encode "A" with "0", "B" with "10", "C" with "110", and "D" with "111". 
5 * 1 + 1 * 2 + 1 * 3 + 1 * 3 = 13 
若选择G++提交,输出double 一定要用%f

#include <iostream> #include <cstdio> #include <string> #include <queue>#include <functional>using namespace std;int main(){//freopen("data.out", "w", stdout);string str;while((cin >> str) && str != "END") {int w[128] = {0};for (int i = 0; i < str.length(); ++i) {w[str[i]]++;}priority_queue<int, vector<int>, greater<int> > pq; for (int i = 'A'; i <= '_'; ++i) {if (w[i]) {pq.push(w[i]); }}int sum = 0;while(pq.size() > 1) {int a = pq.top(); pq.pop();int b = pq.top();pq.pop();sum += (a + b);pq.push(a + b);}pq.pop();if (!sum) {sum = str.length();}printf("%d %d %.1lf\n", str.length() * 8, sum, (str.length() * 8.0) / (double)sum);}return 0;}


1521

Language:
Entropy
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 7923 Accepted: 2934

Description

An entropy encoder is a data encoding method that achieves lossless data compression by encoding a message with "wasted" or "extra" information removed. In other words, entropy encoding removes information that was not necessary in the first place to accurately encode the message. A high degree of entropy implies a message with a great deal of wasted information; english text encoded in ASCII is an example of a message type that has very high entropy. Already compressed messages, such as JPEG graphics or ZIP archives, have very little entropy and do not benefit from further attempts at entropy encoding. 

English text encoded in ASCII has a high degree of entropy because all characters are encoded using the same number of bits, eight. It is a known fact that the letters E, L, N, R, S and T occur at a considerably higher frequency than do most other letters in english text. If a way could be found to encode just these letters with four bits, then the new encoding would be smaller, would contain all the original information, and would have less entropy. ASCII uses a fixed number of bits for a reason, however: it’s easy, since one is always dealing with a fixed number of bits to represent each possible glyph or character. How would an encoding scheme that used four bits for the above letters be able to distinguish between the four-bit codes and eight-bit codes? This seemingly difficult problem is solved using what is known as a "prefix-free variable-length" encoding. 

In such an encoding, any number of bits can be used to represent any glyph, and glyphs not present in the message are simply not encoded. However, in order to be able to recover the information, no bit pattern that encodes a glyph is allowed to be the prefix of any other encoding bit pattern. This allows the encoded bitstream to be read bit by bit, and whenever a set of bits is encountered that represents a glyph, that glyph can be decoded. If the prefix-free constraint was not enforced, then such a decoding would be impossible. 

Consider the text "AAAAABCD". Using ASCII, encoding this would require 64 bits. If, instead, we encode "A" with the bit pattern "00", "B" with "01", "C" with "10", and "D" with "11" then we can encode this text in only 16 bits; the resulting bit pattern would be "0000000000011011". This is still a fixed-length encoding, however; we’re using two bits per glyph instead of eight. Since the glyph "A" occurs with greater frequency, could we do better by encoding it with fewer bits? In fact we can, but in order to maintain a prefix-free encoding, some of the other bit patterns will become longer than two bits. An optimal encoding is to encode "A" with "0", "B" with "10", "C" with "110", and "D" with "111". (This is clearly not the only optimal encoding, as it is obvious that the encodings for B, C and D could be interchanged freely for any given encoding without increasing the size of the final encoded message.) Using this encoding, the message encodes in only 13 bits to "0000010110111", a compression ratio of 4.9 to 1 (that is, each bit in the final encoded message represents as much information as did 4.9 bits in the original encoding). Read through this bit pattern from left to right and you’ll see that the prefix-free encoding makes it simple to decode this into the original text even though the codes have varying bit lengths. 

As a second example, consider the text "THE CAT IN THE HAT". In this text, the letter "T" and the space character both occur with the highest frequency, so they will clearly have the shortest encoding bit patterns in an optimal encoding. The letters "C", "I’ and "N" only occur once, however, so they will have the longest codes. 

There are many possible sets of prefix-free variable-length bit patterns that would yield the optimal encoding, that is, that would allow the text to be encoded in the fewest number of bits. One such optimal encoding is to encode spaces with "00", "A" with "100", "C" with "1110", "E" with "1111", "H" with "110", "I" with "1010", "N" with "1011" and "T" with "01". The optimal encoding therefore requires only 51 bits compared to the 144 that would be necessary to encode the message with 8-bit ASCII encoding, a compression ratio of 2.8 to 1. 

Input

The input file will contain a list of text strings, one per line. The text strings will consist only of uppercase alphanumeric characters and underscores (which are used in place of spaces). The end of the input will be signalled by a line containing only the word “END” as the text string. This line should not be processed.

Output

For each text string in the input, output the length in bits of the 8-bit ASCII encoding, the length in bits of an optimal prefix-free variable-length encoding, and the compression ratio accurate to one decimal point.

Sample Input

AAAAABCDTHE_CAT_IN_THE_HATEND

Sample Output

64 13 4.9144 51 2.8

1751

Language:
Highways
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 15472 Accepted: 4470 Special Judge

Description

The island nation of Flatopia is perfectly flat. Unfortunately, Flatopia has a very poor system of public highways. The Flatopian government is aware of this problem and has already constructed a number of highways connecting some of the most important towns. However, there are still some towns that you can't reach via a highway. It is necessary to build more highways so that it will be possible to drive between any pair of towns without leaving the highway system. 

Flatopian towns are numbered from 1 to N and town i has a position given by the Cartesian coordinates (xi, yi). Each highway connects exaclty two towns. All highways (both the original ones and the ones that are to be built) follow straight lines, and thus their length is equal to Cartesian distance between towns. All highways can be used in both directions. Highways can freely cross each other, but a driver can only switch between highways at a town that is located at the end of both highways. 

The Flatopian government wants to minimize the cost of building new highways. However, they want to guarantee that every town is highway-reachable from every other town. Since Flatopia is so flat, the cost of a highway is always proportional to its length. Thus, the least expensive highway system will be the one that minimizes the total highways length. 

Input

The input consists of two parts. The first part describes all towns in the country, and the second part describes all of the highways that have already been built. 

The first line of the input file contains a single integer N (1 <= N <= 750), representing the number of towns. The next N lines each contain two integers, xi and yi separated by a space. These values give the coordinates of ith town (for i from 1 to N). Coordinates will have an absolute value no greater than 10000. Every town has a unique location. 

The next line contains a single integer M (0 <= M <= 1000), representing the number of existing highways. The next M lines each contain a pair of integers separated by a space. These two integers give a pair of town numbers which are already connected by a highway. Each pair of towns is connected by at most one highway. 

Output

Write to the output a single line for each new highway that should be built in order to connect all towns with minimal possible total length of new highways. Each highway should be presented by printing town numbers that this highway connects, separated by a space. 

If no new highways need to be built (all towns are already connected), then the output file should be created but it should be empty. 

Sample Input

91 50 0 3 24 55 10 45 21 25 331 39 71 2

Sample Output

1 63 74 95 78 3

3032

Card Trick
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 4312 Accepted: 3049

Description

The magician shuffles a small pack of cards, holds it face down and performs the following procedure:

  1. The top card is moved to the bottom of the pack. The new top card is dealt face up onto the table. It is the Ace of Spades.
  2. Two cards are moved one at a time from the top to the bottom. The next card is dealt face up onto the table. It is the Two of Spades.
  3. Three cards are moved one at a time…
  4. This goes on until the nth and last card turns out to be the n of Spades.

This impressive trick works if the magician knows how to arrange the cards beforehand (and knows how to give a false shuffle). Your program has to determine the initial order of the cards for a given number of cards, 1 ≤ n ≤ 13.

Input

On the first line of the input is a single positive integer, telling the number of test cases to follow. Each case consists of one line containing the integer n.

Output

For each test case, output a line with the correct permutation of the values 1 to n, space separated. The first number showing the top card of the pack, etc…

Sample Input

245

Sample Output

2 1 4 33 1 4 5 2

by wjsay



原创粉丝点击