1. 矩阵对角线元素和
#include<bits/stdc++.h>
using namespace std;
int main(){
int m;
cin>>m;
int matrix[m+1][m+1];
for(int i=1;i<=m;++i){
for(int j=1;j<=m;++j){
cin>>matrix[i][j];
}
}
int sum=0;
for(int i=1;i<=m;++i){
sum+=matrix[i][i];
}
cout<<"主对角线: "<<sum<<endl;
sum=0;
for(int i=1;i<=m;++i){
sum+=matrix[i][m-i+1];
}
cout<<"副对角线: "<<sum;
return 0;
}
2. 字符统计
#include<bits/stdc++.h>
using namespace std;
int cnt1,cnt2,cnt3;
string str;
int main(){
cin>>str;
for(int i=0;i<str.length();++i){
if(str[i]>='0'&&str[i]<='9'){
cnt1++;
}else if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')){
cnt2++;
}else{
cnt3++;
}
}
cout<<"数字字符个数: "<<cnt1<<endl;
cout<<"字母字符个数: "<<cnt2<<endl;
cout<<"其他类型字符个数: "<<cnt3;
return 0;
}
3. 候选人得票统计
#include<bits/stdc++.h>
using namespace std;
int m,n;
string name;
map<string,int> mp;
int main(){
cin>>m>>n;
for(int i=0;i<m;++i){
cin>>name;
mp[name]++;
}
for(map<string,int>::iterator i=mp.begin();i!=mp.end();++i){
cout<<i->first<<": "<<i->second<<endl;
}
return 0;
}
4. 链表
#include<bits/stdc++.h>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
int fun(LinkList L,int x){
int cnt=0;
LNode *p=L;
while(p){
if(p->data==x){
++cnt;
}
p=p->next;
}
return cnt;
}
int main(){
LinkList L = new LNode;L->data=2;
LNode *node1 = new LNode;node1->data=2;
LNode *node2 = new LNode;node2->data=1;
LNode *node3 = new LNode;node3->data=3;
LNode *node4 = new LNode;node4->data=1;
L->next=node1;
node1->next=node2;
node2->next=node3;
node3->next=node4;
node4->next=NULL;
cout<<fun(L,1);
return 0;
}