编程学习历程
一、数据结构小知识点
lock():捕捉从程序开始到clock()被调用时所消耗的时间。这个时间单位是clock tick,即“时钟打点”。
常数CLK_TCK:机器时钟每秒所走的时钟打点数。
模板:
#include<stdio.h>
#include<time.h>
#include<math.h>
#include
using namespace std;
clock_t start,stop;/clock_t是clock()函数返回的数据类型/
double duration;/记录被测函数运行时间,以秒为单位/
int main()
{/不在测试范围内的准备工作写在clock()调用之前/
start=clock();/开始计时/
Myfunction();
stop=clock(); /其他不在测试范围的处理写在后面,例如输出duration的值/
duration=((double)(stop-start))/CLK_TCK;/计算运行时间/
return 0;
}
二、题目
今天做的是哈学院冬令营的题
A - The puzzle
Kayaking is playing a puzzle game containing n different blocks. He marks the blocks with integers from 1 to n, which show the blocks’ original positions. Each time he can exchange two blocks and he wants to know how many times he needs at least to restore the puzzle.
Input
The input starts with one line contains exactly one positive integer which is the number of test cases.
Each test case contains two lines.
The first line contains an integer, which indicates the number of puzzle pieces.
The second line contains n different integers, the i-th number means the mark of the block in the i-th position.
Output
For each test case, output one line with one number represents the minimum operations.
Sample Input
2
4
2 3 4 1
4
2 1 4 3
Sample Output
3
2
想法:看到这题之后第一想法就是冒泡排序,属实easy了,仔细分析了样例的输入输出格式之后,想到了用一下计数器,写完之后看到这么多的for循环,就十分害怕~会不会超时。
代码如下:
#include <stdio.h>
#include
using namespace std;
int a[100000], b[10000];
int main() {
int k, n, temp, flag = 0;
cin >> k;
for (int i = 1; i <= k; i++) {
cin >> n;
for (int j = 1; j <= n; j++) {
cin >> a[i];
}
for (int j = 1; j <= n; j++) {
for (int m = j; m <= n - 1; m++) {
if (a[j] > a[m + 1]) {
temp = a[j];
a[j] = a[m + 1];
a[m + 1] = temp;
flag++;
}
}
}
b[i] = flag;
flag = 0;
}
for (int i = 1; i <= k; i++) {
cout << b[i] << endl;;
}
return 0;
}
虽然输出结果是对的,但是没通过……