C language algorithm learning (pointer, structure, mathematical calculation)

This article will start from 7 sample questions and describe my learning about algorithms today

A - Maya Calendar

Problem restatement

Last weekend, Professor MA Ya made a major discovery about the ancient Maya. From an ancient knot rope (a tool used by the Mayans to record things), the professor discovered that the Mayans used the Haab calendar, which has 365 days in a year. The Haab calendar has 19 months per year. In the first 18 months, there are 20 days in each month. The names of the months are pop, no, zip, zotz, tzec, xul, yoxkin,mol, chen, yax, zac, ceh, mac , kankin, muan, pax, koyab, cumhu. The dates in these months are represented by 0 to 19; the last month of the Haab calendar is called uayet, which has only 5 days and is represented by 0 to 4. The Mayans considered the month with the fewest dates to be unlucky: In this month, courts are not held, people are not engaged in transactions, or even cleaning houses.
For religious reasons, the Maya also used another calendar. The middle of this calendar is called the Tzolkin calendar (holly year). The year is divided into 13 different periods, each period has 20 days, and each day uses a number. It is expressed in a combined form with a word. The numbers used are 1~13, and there are 20 words used. They are: imix, ik,akbal, kan, chicchan, cimi, manik, lamat, muluk, ok, chuen, eb, ben, ix,mem, cib , caban, eznab, canac, ahau. Note: Each day of the year has a clear and unique description. For example, at the beginning of the year, the date is described as follows: 1 imix, 2 ik, 3 akbal, 4 kan, 5 chicchan, 6 cimi, 7 manik, 8 lamat, 9 muluk, 10ok, 11 chuen, 12 eb, 13 ben, 1 ix, 2 mem, 3 cib, 4 caban, 5 eznab, 6canac, 7 ahau, 8 imix, 9 ik, 10 akbal...That is to say, numbers and words are
used in cycles independently .
The years in the Haab calendar and the Tzolkin calendar are represented by the numbers 0, 1, ..., and the number 0 indicates the beginning of the world. So the first day is expressed as:
• Haab: 0. pop 0
• Tzolkin: 1 imix 0
Please help Professor MA Ya to write a program to transform the Haab calendar into a Tzolkin calendar.

enter

• The data in the Haab calendar is represented by the following methods:
• NumberOfTheDay. Month Year (date. Month Year)
• The first line in the input indicates the amount of data of the Haab calendar date to be converted. Each subsequent line
represents a date, and the number of years is less than 5000.

Output

• The data in the Tzolkin calendar is represented in the following ways:
• Number NameOfTheDay Year (day number day name year number)
• The first line represents the number of dates output. Each row below represents a date in the corresponding Tzolkin calendar in the input data.

Problem solving ideas

Find the total number of days under the haab chronology, and then convert it to the tzolkin chronology.
It is worth noting that the haab memorial method counts from 0 every month.
First set two string functions haab and tzolin to complete the conversion of month name and month number, then set a structure array to record the time, and finally calculate the sum of days and convert it to tzolkin output.

Source code

#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
const int N = 5000;
struct data {
    
    
	int year,day;
	string month;
} p[N];
int n;
int main() {
    
    
	string haab[] = {
    
    "pop","no","zip","zotz","tzec",
	                 "xul","yoxkin","mol","chen","yax","zac","ceh",
	                 "mac","kankin","muan","pax","koyab","cumhu","uayet"
	                };
	string tzo[] = {
    
    "imix","ik","akbal","kan","chicchan","cimi",
	                "manik","lamat","muluk","ok","chuen","eb","ben","ix",
	                "mem","cib","caban","eznab","canac","ahau"
	               };
	cin>>n;
	cout<<n<<endl;
	for(int i = 1; i <= n; ++i) {
    
    
		scanf("%d. ",&p[i].day);
		cin>>p[i].month;
		cin>>p[i].year;
		int year,month,day,t,cnt;
		for(int j = 0; j<19; ++j) {
    
    
			if(p[i].month==haab[j]) {
    
    
				t = j;
				break;
			}
		}
		cnt = p[i].year*365+t*20+p[i].day;//计数共过了多少天
		year = cnt/260;// 按tzolki算经历了多少年
		cnt = cnt%260;//算出剩余总天数
		day =cnt%13+1;
		month = cnt%20;
		cout<<day<<" "<<tzo[month]<<" "<<year<<endl;
	}
	return 0;
}

B - Diplomatic License

Problem restatement

In order to minimize diplomatic expenditures, countries around the world discuss as follows. It is not enough for each country to maintain diplomatic relations with at most one country, because there are more than two countries in the world, and some countries cannot communicate with each other through (a series of) diplomats.
• This question assumes that each country maintains diplomatic relations with at most two other countries. Treating every country equally is an unwritten diplomatic practice. Therefore, each country maintains diplomatic relations with the other two countries.
• International topographicalists propose a structure suitable for this need. They will arrange countries to form a circle so that each country can establish diplomatic relations with its two neighbors. In the real world, the Ministry of Foreign Affairs of a country is located in the capital of the country. For the sake of simplicity, this question assumes that the position of the capital is a point on a two-dimensional plane. If you use a straight line to connect the foreign ministries of countries that maintain diplomatic relations
, the result is a polygon.
• Now, we need to set a venue for bilateral diplomatic meetings between two countries. Similarly, for diplomatic reasons, diplomats from the two countries must travel the same distance to the location. In order to improve efficiency, the driving distance should be shortened as much as possible. Please prepare for the bilateral diplomatic conference.
• Input
• Input gives several test cases. Each test case first gives the number n, which means that n countries are involved. This question assumes that n3 is an odd number. Then, n pairs of x and y coordinates are given to indicate the location of the Ministry of Foreign Affairs. The coordinates of the Ministry of Foreign Affairs are integers with absolute values ​​less than 1012. The order of the countries is the same as the order in which they appear in the input. In addition, in the list, the first country is a neighbor of the last country.
• Output
• For each test case, first output the number of countries in the test case (=n), and then give the x and y coordinates of the location of the bilateral diplomatic conference between countries. The order of the output meeting locations should be the same as the order given in the input. Starting from the meeting place of the top two countries, it continues to the meeting place of the last two countries, and finally the meeting place of the nth country and the first country is output.

(In simple terms, calculate the midpoint of two adjacent numbers)

problem analysis

Follow the following ideas:

  1. Define the structure to record the x and y coordinates
  2. Set a structure last, and read into last whenever there is a new number.
  3. Calculate the average value of last and the structure variable now that records the previous set of numbers and output
  4. Now=last
    should be treated specially for the first number, because the first-to-last comparison is required, an f structure irst is set to record the first group number.

Source code:

#include<cstdio>
#include<iostream>
using namespace std;
struct point {
    
    
	long long int x;
	long long int y;
};
int main() {
    
    
	struct point now,first,last;
	int n=0;
	while(~scanf("%d",&n)){
    
    
		printf("%d ",n);
		cin >>first.x >>first.y;
		now=first;
		for(int i=1;i<n;i++)
		{
    
    
			cin >>last.x >>last.y ;
			printf("%.6f %.6f ",(last.x+now.x)/2.0,(last.y+now.y)/2.0);
			now=last;
		}
		now=first;
		printf("%.6f %.6f\n",(last.x+now.x)/2.0,(last.y+now.y)/2.0);
	}`在这里插入代码片`
	return 0;
	}

In this question, I made the following mistakes:
1. The output format is a floating-point number, and I have not forced a type conversion, and there is no 2 plus a decimal point
2.x, and y is not defined as long long.

The following two questions are the use of pointers

C.“Accordian” Patience

Problem restatement

Please imitate the "Accordian" Patience game. The rules are as follows:
• Players will deal a deck of cards one by one, in a row from left to right, without overlapping. As long as a playing card matches the first card from the left or the third card from the left, move this playing card on top of the matched card. The so-called two-card match means that the two cards have the same value (number or letter) or the same suit. Whenever you move a card, check to see if the card can continue to move to the left, and only move the card at the top of the deck each time. In this game, two piles can be turned into one pile. If according to the rules, the cards from the right pile can be moved to the left pile one by one, and it can become one pile. This game moves the cards to the left as much as possible. If there is only one deck at the end, the player wins.
• During the game, players may encounter a situation where there are multiple choices at once. When both cards can be moved, the leftmost card is moved. If a card can move one position to the left or three positions to the left, move it three positions.

enter

• Enter the order in which the cards are given out. Each test case consists of a pair of rows, each row gives 26 cards, separated by a single space character. The last line of the input file gives a # as its first character. Each playing card is represented by two characters. The first character is the face value (A=Ace, 2-9, T=10, J=Jack, Q=Queen, K=King), and the second character is the suit (C= Clubs (梅花), D=Diamonds ( Squares), H=Hearts (hearts), S=Spades (spades)).

Output

• For each pair of rows in the input (52 cards of a deck of playing cards), output one row, giving the number of cards remaining in each pile of playing cards after the corresponding input row is played.
I don’t have AC for this question, so skip

D - Broken Keyboard

Problem restatement

You are typing a long text with a bad keyboard. The problem with this keyboard is that from time to time the "Home" key or "End" key is automatically pressed when you enter text. You are not aware of this problem, because you only focus on the text and you don't even turn on the display. After you finish typing, you turn on the monitor and see the text on the screen. In Chinese, we call it tragedy. Please find the text of the tragedy.

enter

• Enter several test cases. Each test case is a line, containing at least one, up to 100,000 letters, underscores and two special characters'[' and']'; where'[' means "Home" key, and']' means "End" key . The input ends with EOF.

Output

• For each test case, output tragedy of the text on the screen
the Sample the Input
This_is_a_ [Beiju] _TEXT
[[]] [] [] Happy_Birthday_to_Tsinghua_University
the Sample the Output
BeijuThis_is_a__text
Happy_Birthday_to_Tsinghua_University

This question also has no ac, do not evaluate, skip

E - Satellites

Problem restatement

Insert picture description here

enter

• The input contains one or more test cases.
• One line for each test case, giving two integers s and a, and a string "min" or "deg"; where s is the distance between the artificial satellite and the earth's surface, and a is the distance between the two artificial satellites to the center of the earth Angle. In minutes (′), or in degrees (◦), as the unit. The input will not give both points and degrees.

Output

• For each test case, output one line, giving the arc distance and linear chord distance between the two satellites in kilometers. The distance is a floating point number, which stores six digits after the decimal point.

problem analysis

Mathematical calculation problems need to understand the problem and list the formulas.
Insert picture description here
You can use 360° subtraction to deal with angles exceeding 180°

#include<iostream>
#include<cmath>
using namespace std;
double s,a;
string op;
//acos(-1)表示Π
int main() {
    
    
	while(cin >> s >> a >> op) {
    
    
		if(op == "min") a /= 60;
		if(a > 180) a = 360 - a;
		double arcdist = 2*acos(-1)*(s+6440.0)*a/360;
		double chord_dist = (s + 6440.0)*sin(a*acos(-1)/360)*2;
		printf("%.6lf %.6lf\n",arcdist,chord_dist);
	}
	return 0;
}

G - The Circumference of the Circle

Problem restatement

• To calculate the circumference of a circle seems to be an easy task, as long as you know the diameter of the circle. But what if you don’t know? Give the Cartesian coordinates of 3 non-collinear points on the plane. Your job is to calculate the perimeter of the only circle that intersects these 3 points.

enter

• The input contains one or more test cases, each test case on a line, including 6 real numbers x1, y1, x2, y2, x3, y3, representing the coordinates of 3 points. The diameter determined by these 3 points does not exceed 1 million. Input is terminated at the end of the file.

Output

• For each test case, output one line and give a real number that represents the circumference of the circle determined by 3 points. The output circumference is accurate to two decimal places. The value of Pi is 3.141592653589793.

problem analysis

Helen formula, my god
Insert picture description here

Source code

#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
double xa,ya,xb,yb,xc,yc,p;
double getDistance(double x,double y,double xx,double yy) {
    
    
	return sqrt(pow(x-xx,2)+pow(y-yy,2));
}
int main() {
    
    
	while(cin >> xa >> ya >> xb >> yb >> xc >> yc) {
    
    
		double a = getDistance(xa,ya,xb,yb);
		double b = getDistance(xb,yb,xc,yc);
		double c = getDistance(xa,ya,xc,yc);
		double p = (a+b+c)/2;
		double s = sqrt(p*(p-a)*(p-b)*(p-c));
		double d = a*b*c/2.0/s;
		printf("%.2f\n",d*acos(-1.0));
	}
	return 0;
}

to sum up

I have insufficient grasp of linked lists, insufficient use, and I am not familiar with the common function libraries and functions of C, so I should improve

Guess you like

Origin blog.csdn.net/seekerzhz/article/details/112853063