/*
*@author: LeeG
*@date: 2020-12-10
*/
1. C语言和C++的区别
©面向过程语言:面向过程编程就是分析出解决问题的步骤,然后把这些步骤一步一步的实现,使用的时候一个一个的依次调用就可以了。
(C++)面向对象语言:面向对象编程就是把问题分解成各个对象,建立对象的目的不是为了完成一个步骤,而是为了描述某个事物在整个解决问题的步骤中的行为。
2. C++头文件及常用头文件介绍
#include <iostream>
using namespace std;
int main(){
//please write your code!
return 0;
}
#include <iostream>
#include <cmath> //数学公式 例如绝对值abs()、幂函数pow()...
#include <string> //C++字符串
#include <string.h> //C语言库,对应C++是cstring
#include <algorithm> //常用函数,max()、min()、abs()、swap()、sort()...
#include <bits/stdc++.h> //万能头文件
using namespace std;
int main(){
//please write your code!
return 0;
}
更多头文件及C++ 标准模板库STL看下面链接:
3. C++输入与输出
#include <iostream>
using namespace std;
int main(){
int a;
char b;
float c;
cin>>a>>b>>c;
cout<<"1:"<<a<<b<<c<<endl;
string str;
cin>>str;
cout<<"2:"<<str<<endl;
getline(cin, str);
cout<<"3:"<<str<<endl;
//思考1 上述的cin>>str和getline(cin, str); 有什么区别?
//思考2 如果要输入 19:05 怎么输入?
//思考3 如果题目要求输入一串数字,以回车结束输入,怎么输入?
return 0;
}
思考3非常重要,写题经常遇到!!!
思考3总结,看文章:
4. 代码格式规范
为什么这个多次强调?当你写代码出现bug时,整洁、不乱的代码能帮助你快速找到它。从心理上也会舒适很多。不仅如此,以后复习或者别人阅读你代码时,提高可读性~
#include <bits/stdc++.h>
#include <vector>
using namespace std;
struct Graph{
int edge;
int weight;
Graph(int e, int w){
edge = e;
weight = w;
}
};
int main(){
int n, m, sx, sy;
cin>>n>>m>>sx>>sy;
int cs[n]; //记录救援队数目
int judge[n]; //记录该城市是否达到过
int dotlist[n]; //记录权值
int pre[n]; //记录行走路径
int path[n]; //记录最短路径条数
memset(path, 0, sizeof(path));
memset(pre, 0, sizeof(pre));
memset(dotlist, 0, sizeof(dotlist));
memset(judge, 0, sizeof(judge));
int res[n];
fill(res, res+n, 501);
for(int i = 0; i < n; i++){
cin>>cs[i];
}
vector<Graph> s[n];
for(int i = 0; i < m; i++){
int a, b, c;
cin>>a>>b>>c;
s[a].push_back(Graph(b, c));
s[b].push_back(Graph(a, c));
}
res[sx] = 0;
dotlist[sx] = cs[sx];
path[sx] = 1;
int flag = 0; //记录目前城市的下标
for(int i = 0; i < n; i++){
int min = 502;
for(int j = 0; j < n; j++){
if(!judge[j] && res[j] < min){
min = res[j];
flag = j;
}
}
int num = res[flag];
judge[flag] = 1;
for(int j = 0; j < s[flag].size(); j++){
int e = s[flag][j].edge;
int w = s[flag][j].weight;
if(!judge[e] && num + w < res[e]){
res[e] = num + w;
dotlist[e] = dotlist[flag] + cs[e];
pre[e] = flag;
path[e] = path[flag];
}else if(num + w == res[e]){
path[e] += path[flag];
if(dotlist[flag] + cs[e] > dotlist[e]){
dotlist[e] = dotlist[flag] + cs[e];
pre[e] = flag;
}
}
}
}
memset(res, 0, sizeof(res));
int r = sy, k = 0;
while(r != sx){
res[k++] = pre[r];
r = pre[r];
}
cout<<path[sy]<<' '<<dotlist[sy]<<endl;
for(int i = k-1; i >= 0; i--){
cout<<res[i]<<' ';
}
cout<<sy;
return 0;
}
5. C++写题过程中常用总结
-
函数memset()、fill()的使用
-
字符与数字互转stringstream
-
常见的字符串操作length()、substr()等
-
排序函数sort()的使用及(暂可不接受)结构体排序
/* 小李老师因为有事情要忙,交给小王一个任务,这个任务就是帮他把几个学生排好序 排序规则按照年级降序排序,如果年级相同则按照姓名升序排序,如果姓名相同则按照年龄降序排序。 输入 第一行给出学生总人数N, 接下来N行给出每个学生信息,格式:年级 姓名 年龄 输出 按照排序规则输出学生信息 输入样例 1 2 2 wps 20 2 lsn 8 输出样例 1 lsn 8 wps 20 */
-
解题过程中容易遇到的坑!