題目
分析題目:
兩個數字相加,然後需要以一定格式輸出。先求相加,然後把數字一個個對10取模輸出,相對比較容易。用棧做一個後進後出就好了。
代碼:
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
stack<char> sta;
int main()
{
int a, b;
cin >> a >> b;
int result;
result = a + b;
int n = abs(result);
int flag = -1;
while(n)
{
int c = 0;
c = n%10;
flag++;
n /= 10;
// cout << n << " " << flag << endl;
if(flag == 3)
{
int sign = ',';
sta.push(sign);
flag = 0;
}
sta.push(c+'0');
}
if(result<0)
cout << "-";
if(result == 0)
cout << "0";
while(!sta.empty())
{
char d = sta.top();
cout << d;
sta.pop();
}
cout << endl;
return 0;
}
總結:
做的時候沒用對容器,從vector到queue最後纔是stack,下次動手之前先分析好題目。
pat1002
題目
分析題目
兩個多項式相加,輸出相應多項式項數和係數,用map即可完成對應
代碼(未AC)
#include <iostream>
#include <map>
#include <cstdio>
using namespace std;
map<int,double, greater<int> > vec;
int main()
{
int k1;
cin >> k1;
while(k1--)
{
int N;
double a;
cin >> N >> a;
vec[N] = a;
}
int k2;
cin >> k2;
while(k2--)
{
int N;
double a;
cin >> N >> a;
map<int, double>::iterator it;
it = vec.find(N);
if(it == vec.end())
vec[N] = a;
else
vec[N] += a;
}
cout << vec.size();
for(map<int, double>::iterator it = vec.begin(); it != vec.end(); it++)
printf(" %d %.1lf", it->first, it->second);
cout << endl;
return 0;
}
總結:
重新熟練了map的插入、遍歷操作,其中還用了一個對key值降序排列的重定義。注意題目對小數位的輸出要求。但不知道爲什麼沒有AC