string中的stringstream

博客:

加速:ios::sync_with_stdio(false);

举个例子:

 

題目:输入的第一行有一个数字 N 代表接下來有 N 行资料,每一行资料里有不固定个数的整数(最多20个,每行最大200个字元),编程將每行的总和打印出來。

输入:

3
1 2 3
20 17 23 54 77 60
111 222 333 444 555 666 777 888 999

输出:

6
251
4995

代码:

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
 
int main()
{
    string s;
    stringstream ss;
    int n;
 
    cin >> n;
    getline(cin, s);  //读取换行
    for (int i = 0; i < n; i++)
    {
        getline(cin, s);
        ss.clear();
        ss.str(s);
 
        int sum = 0;
 
        while (1)
        {
            int a;
 
            ss >> a;
            if(ss.fail())
                break;
            sum += a;
        }
        cout << sum << endl;
    }
 
    return 0;
}
View Code

字典树的结合

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<sstream>
using namespace std;
const int max_=2e4+5;
int tot;
int trie[max_][26];
bool book[max_];
void insert(string str)
{
    int len=str.size();
    int rt=0;
    for(int i=0;i<len;i++)
    {
        int k=str[i]-'a';
        if(!trie[rt][k])
            trie[rt][k]=++tot;
        rt=trie[rt][k];
    }
    book[rt]=1;
}
bool find_(string str)
{
    int len=str.size();
    int rt=0;
    for(int i=0;i<len;i++)
    {
        int k=str[i]-'a';
        if(!trie[rt][k])
            return 0;
        rt=trie[rt][k];
    }
   if(book[rt])
    return 1;
   else
    return 0;
}
int main()
{
    ios::sync_with_stdio(false);
    string str1,str2;
    while(getline(cin,str1))
    {
        if(str1=="#")
            break;
        tot=0;
        int ant=0;
        memset(trie,0,sizeof(trie));
        memset(book,0,sizeof(book));
        stringstream ss(str1);
        while(ss>>str2)
        {
            //cout<<ss<<endl;
            if(!find_(str2))
            {
                ant++;
                insert(str2);
            }
        }
        printf("%d\n",ant);
    }
}
View Code

 

转载于:https://www.cnblogs.com/linhaitai/p/9942733.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值