1.生成水仙花数组
#include <iostream>
#include <cmath>
using namespace std;
const int N = 3;
const int MAXN = 6;
const int BASE = 10;
int main()
{
cout << "int dn[]={";
int count=0;
for(int i=N; i<=MAXN; i++) {
int start = 1, end;
for(int j=1; j<i; j++)
start *= BASE;
end = start * BASE;
for(int j=start; j<end; j++) {
int v=j, dn=0;
while(v) {
dn += pow(v % 10, (double)i);
v /= BASE;
}
if(dn == j) {
if(++count != 1)
cout << ", ";
cout << j;
}
}
}
cout << "};" << endl;
return 0;
}
2.畅通工程(队列/Kruskal(克鲁斯卡尔)算法)
#include <iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int N=101;
int minsum=100000;
int f[N+1];
void Finit(int n)
{
for(int i=1;i<=n;i++)
f[i]=i;
}
int Find(int a)
{
return a==f[a]?a:f[a]=Find(f[a]);
}
bool Union(int a,int b)
{
a=Find(a);
b=Find(b);
if(a!=b)
{
f[a]=b;
return true;
}
else
return false;
}
struct edge
{
int src,dest,cost;
bool operator < (const edge& n) const {
return cost>n.cost;
}
};
int main()
{
edge e;
int n,m;
while(scanf("%d",&n)!=EOF && n)
{
priority_queue<edge> q;
Finit(n);
m=n*(n-1)/2;
while(m--)
{
scanf("%d%d%d",&e.src,&e.dest,&e.cost);
q.push(e);
}
int ans=0,count=0;
while(!q.empty())
{
e=q.top();
q.pop();
if(Union(e.src,e.dest))
{
count++;
ans+=e.cost;
}
if(count==n-1)
break;
}
cout<<ans<<endl;
}
return 0;
}
3.简单计算器
#include <iostream>
#include <string>
#include <stack>
#include <cctype>
#include <cstdio>
using namespace std;
int main()
{
string s;
stack<char> op;
stack<double> operand;
double operand1, operand2;
while(getline(cin, s) && s != "0") {
for(int i=0; s[i]; i++) {
if(isdigit(s[i])) {
operand1 = 0;
while(isdigit(s[i])) {
operand1 = operand1 * 10 + s[i] - '0';
i++;
}
i--;
operand.push(operand1);
} else if(s[i] == '+' || s[i] == '-') {
if(op.empty())
op.push(s[i]);
else {
char sop = op.top();
op.pop();
operand2 = operand.top();
operand.pop();
operand1 = operand.top();
operand.pop();
if(sop == '+')
operand.push(operand1 + operand2);
else
operand.push(operand1 - operand2);
op.push(s[i]);
}
} else if(s[i] == '*' || s[i] == '/') {
char cop = s[i];
i += 2;
operand2 = 0;
while(isdigit(s[i])) {
operand2 = operand2 * 10 + s[i] - '0';
i++;
}
i--;
operand1 = operand.top();
operand.pop();
if(cop == '*')
operand.push(operand1 * operand2);
else
operand.push(operand1 / operand2);
}
}
while(!op.empty()) {
char sop = op.top();
op.pop();
operand2 = operand.top();
operand.pop();
operand1 = operand.top();
operand.pop();
if(sop == '+')
operand.push(operand1 + operand2);
else
operand.push(operand1 - operand2);
}
printf("%.2f\n", operand.top());
}
return 0;
}
4.最大报销额(未解决)