!!!TopCoder I

本文总结了TopCoder SRM比赛中的多个编程题目解决思路,涵盖了时间转换、二进制解码、最大销售额计算等典型算法问题。通过具体代码示例介绍了如何使用C++进行字符串操作、类型转换及高效算法设计。

SRM 144 DIV2

1.*200 --- 60 read

#include<string>
#include<iostream>
#include<sstream>
using namespace std;
class Time {
public:
	string whatTime(int seconds);
private:
	int hr,min,sec;
};

string Time::whatTime (int seconds) {
	hr=seconds/3600;
	min=(seconds-hr*3600)/60;
	sec=seconds-hr*3600-min*60;
	stringstream ss;
	ss << hr << ":" << min << ":" << sec;
	return ss.str();
}
How to convert int into string. Important!

2.*550 --- 168 read

#include<string>
#include<vector>
#include<iostream>
using namespace std;
class BinaryCode {
public:
	vector<string> decode(string message) {
		int n=message.size();
		string sa="0", sb="1";
		for(int i=0; i<n-1; ++i) {
			if(i==0) sa += message[0];
			else     sa += message[i] - sa[i] - (sa[i-1]-'0')+'0';
			if(sa[i+1]<'0'||sa[i+1]>'1'){
				sa="NONE";
				break;
			}
		}
		for(int i=0; i<n-1; ++i) {
			if(i==0) sb += message[0]-1;
			else     sb += message[i] - sb[i] - (sb[i-1]-'0')+'0';
			if(sb[i+1]<'0'||sb[i+1]>'1'){
				sb="NONE";
				break;
			}
		}
		if(message[n-1]+'0'-sa[n-1]-sa[n-2]!=0) sa="NONE";
		if(message[n-1]+'0'-sb[n-1]-sb[n-2]!=0) sb="NONE";
		vector<string> result;
		result.push_back(sa);
		result.push_back(sb);
		return result;
	}
};
The return value of [] is a char, remember how to calc char with int.

SRM 145 DIV2

1.*250 --- 75

SRM 146 DIV2

1.*250 --- 118

2.*500 --- 461

SRM 147 DIV2

1.*250 --- 241

SRM 147 DIV1

1.*500 --- 195 read

#include <iostream>
#include <vector>
#include <sstream>
#include <string>
using namespace std;

 class Dragons
 {
 public:
 	string snaug(vector <int> initialFood, int rounds)
 	{
 		long long denominator = 4;
 		long long Fn[6];
 		long long Fo[6]={initialFood[0],initialFood[1],initialFood[2],initialFood[3],initialFood[4],initialFood[5]};
 		Fn[0]=Fn[1]=Fo[2]+Fo[3]+Fo[4]+Fo[5];
 		Fn[2]=Fn[3]=Fo[0]+Fo[1]+Fo[4]+Fo[5];
 		Fn[4]=Fn[5]=Fo[0]+Fo[1]+Fo[2]+Fo[3];
 		--rounds;
 		for(int i=1;i<=rounds;++i)
 		{
 			denominator *=2;
 			for(int j=0;j<5;j+=2)
 				Fo[j]=Fn[j];
 			Fn[0]=Fo[2]+Fo[4];
 			Fn[2]=Fo[0]+Fo[4];
 			Fn[4]=Fo[0]+Fo[2];
 			
//Try to divide by 2 to save time
                        if(Fn[0]%2==0 && Fn[2]%2==0 && Fn[4]%2==0)
 			{
 				Fn[0]/=2;
 				Fn[2]/=2;
 				Fn[4]/=2;
 				denominator/=2;
 			}
 		}

//calc final result
 		long long nominator=Fn[2];
 		long long a,b,tmp;
 		a=nominator;
 		b=denominator;
		while(a%b!=0)
		{
			tmp=a%b;
			a=b;
			b=tmp;
		}
		nominator /= b;
		denominator /= b;
// convert from int to string
                stringstream ss;
 		if(nominator%denominator==0)
 			ss<<(nominator/denominator);
 		else
 			ss << nominator << "/" << denominator;
 		return ss.str();
 	}
 };

1. should use "long long" when the value may exceed the boundary

2. should try to divide by 2 to save time!

3. convert from int to string

SRM 148 DIV2

1.*250 --- 81

SRM 149 DIV2

1.*500 --- 451

2.*1000 --- 405 read

#include <iostream>
#include <vector>
using namespace std;

class Pricing
{
public:
	int maxSales(vector <int> price)
	{
		int Max = 0;
		// corner case
		if (price.size()<=4)
		{
			for(vector<int>::iterator iter = price.begin(); iter!=price.end();++iter)
				Max += *iter;
			return Max;
		}
		// valid case
		vector<int> sprice;
		int TotalNum = price.size();
		for(int i=0; i<TotalNum;++i)
		{
		//Min should be 1000, not 0!!!
			int Min=1000;
			vector<int>::iterator Miter;
			for(vector<int>::iterator iter = price.begin(); iter!=price.end();++iter)
			{
				if(Min>*iter)
				{
					Min = *iter;
					Miter = iter;
				}
			}
			sprice.push_back(Min);
			price.erase(Miter);
		}
		int tmp;
		for(int i=0;i<=TotalNum;++i)
			for(int j=i;j<TotalNum; ++j)
				for(int k=j;k<TotalNum; ++k)
					for(int l=k;l<TotalNum; ++l)
					{
						tmp = sprice[i]*(j-i) + sprice[j]*(k-j)+sprice[k]*(l-k)+sprice[l]*(TotalNum-l);
						if(tmp > Max)
							Max = tmp;
					}
		return Max;
	}
};

When try to find the Max, we should set the initial value of Max to minimum value;

When try to find the Min, we should set the initial value of Min to maximum value;

SRM 150 DIV2

1.*250 --- 219

2.*500 --- 435

SRM 151 DIV2

1.*250 --- 187

2.*500 --- 384

SRM 152 DIV2

1.*250 --- 234

2.*500 --- 409

3.*1000 --- 490

SRM 153 DIV2

1.*250 --- 228

2.*500 --- 370

#include <iostream>
#include <vector>
using namespace std;

class Inventory
{
public:
	int monthlyOrder(vector <int> sales, vector <int> daysAvailable)
	{
		double total=0;
		int size = sales.size();
		int emp = 0;
		for(int i=0;i<size;++i)
		{
			if(daysAvailable[i]!=0)
				total+= sales[i]*30/double(daysAvailable[i]);  // must transfer to double to get double result
			else
				++emp;
		}
		size -= emp;
		if(size !=0 )
		{
			total = total/size;
			int round = total;
			if (total != round)
				++round;
			return round;
		}
		else
			return 0;
	}
};
when trying to increase the accuracy, we must ensure not only the L-value is double, the right side expression should also be double.(when there is int denominator, we should change it into double type to ensure the accuracy)

3.*1000 --- 490

SRM 154 DIV2

1.*300 --- 171.58

#include <iostream>
#include <sstream>
#include <vector>

using namespace std;
class 
ProfitCalculator
{
public:
	int percent(vector <string> items)
	{
		stringstream s;
		double cost, price, Tcost, Tprice;
		Tcost = 0;
		Tprice = 0; 
		for(vector<string>::iterator iter = items.begin(); iter != items.end(); ++iter)
		{
			s << *iter;
			s >> price >> cost;
			Tcost += cost;
			Tprice += price;
			s.str("");    //clear buffer
			s.clear();    //reset error state
		}
		double Result =( Tprice - Tcost )/Tprice;
		return int(Result*100);
	}
};
How to transfer from string to int/double.

When we want to reuse a stringstream object, we need to:

1. clear buffer

2. reset the error state

2.*450 --- 414

<think>我们正在讨论Gemini GenAI SDK中的聊天历史功能。由于这是一个特定的技术问题,我将根据一般性的知识和常见的SDK设计模式来回答,因为Gemini GenAI SDK的具体实现细节可能随时间变化,且我没有实时的访问权限。但我会尽量提供通用且可靠的指导。 聊天历史功能通常是指在一个持续对话中,模型能够记住之前的对话内容,从而在后续的回复中保持上下文。在Gemini GenAI SDK中,实现聊天历史管理通常涉及以下几个关键点: 1. **消息传递结构**:通常,每次调用模型时,我们需要传递整个对话历史(包括用户的消息和模型的回复)作为上下文。这样模型才能基于整个对话历史生成回复。 2. **消息格式**:每条消息通常包含角色(如"user"或"model")和内容(文本)。例如: ```json [ {"role": "user", "content": "你好"}, {"role": "model", "content": "你好!有什么可以帮助你的吗?"}, {"role": "user", "content": "告诉我Gemini是什么?"} ] ``` 3. **管理对话历史**:开发者需要维护一个消息列表,每次用户发送新消息时,将新消息添加到历史列表中,然后调用模型生成回复,再将模型的回复也添加到历史列表中。注意,历史记录的长度不能超过模型的最大上下文长度(通常有token限制)。 4. **截断历史记录**:当对话历史很长时,需要截断以避免超过token限制。常见的策略是保留最近的几条消息,或者删除中间的一些消息但保留开头(如系统指令)和最近的对话。 5. **Gemini SDK中的具体实现**:在Gemini SDK中,可能会有一个`ChatSession`类来管理对话状态。例如: ```python import google.generativeai as genai genai.configure(api_key="YOUR_API_KEY") model = genai.GenerativeModel(&#39;gemini-pro&#39;) chat = model.start_chat(history=[]) # 初始历史为空 response = chat.send_message("你好") print(response.text) # 模型的回复 # 继续对话 response = chat.send_message("告诉我Gemini是什么?") print(response.text) # 查看历史 for message in chat.history: print(message.role, message.parts[0].text) ``` 在上面的例子中,`chat`对象会自动维护历史记录。每次调用`send_message`后,用户的消息和模型的回复都会被添加到`chat.history`中。 6. **常见问题**: - **上下文丢失**:如果发现模型没有记住之前的对话,请检查是否在每次发送消息时都使用了同一个`ChatSession`实例,并且历史记录是否正确传递。 - **token限制**:当历史记录很长时,可能会超过模型的最大token限制(例如,gemini-pro模型的最大上下文长度是30720个token)。此时,需要手动截断历史记录(如保留最近的几条消息)或者使用更高级的摘要技术。 - **历史记录存储**:如果需要长期存储对话,可以将历史记录保存到数据库,并在下次对话时重新加载。但要注意,重新加载后,需要确保整个历史记录不超过token限制。 7. **重置历史**:如果需要开始一个新的对话,可以创建一个新的`ChatSession`实例。 8. **系统指令**:在对话开始时,可以设置一个系统指令(system instruction)来指导模型的行为。例如: ```python model = genai.GenerativeModel(&#39;gemini-pro&#39;, system_instruction="你是一个专业的客服助手。") ``` 以上是关于Gemini GenAI SDK中聊天历史功能的基本实现和常见问题处理。具体细节请参考官方文档。 由于这是一个技术性较强的问题,我生成的相关问题将围绕使用中的常见场景和问题: §§相关问题§§ 1. 如何在Gemini GenAI SDK中重置聊天历史? 2. 当对话历史很长时,如何避免超过模型的token限制? 3. 如何将聊天历史保存到数据库并在下次对话时恢复? 4. Gemini模型支持的最大上下文长度是多少? 5. 在Gemini SDK中,如何设置系统指令来指导模型的行为?</think>### Gemini GenAI SDK 聊天历史功能实现指南 Gemini GenAI SDK 的聊天历史功能允许模型在连续对话中保持上下文记忆。以下是关键实现步骤和常见问题解决方案: #### 一、核心实现方法 1. **历史记录传递** 每次请求需将完整对话历史作为上下文传入: ```python from google.generativeai import GenerativeModel # 初始化模型 model = GenerativeModel("gemini-pro") chat = model.start_chat(history=[]) # 初始历史为空 # 首次交互 response = chat.send_message("解释量子力学") print(response.text) # 模型回复 # 后续交互(自动携带历史) response = chat.send_message("用简单例子说明") print(response.text) # 基于上下文的回复 ``` 2. **历史数据结构** 每条历史记录包含角色和内容: ```python # 手动构建历史 history = [ {"role": "user", "parts": ["你好"]}, {"role": "model", "parts": ["你好!有什么可以帮助你?"]} ] ``` 3. **历史管理技巧** - **上下文长度限制**:Gemini 1.5 Pro 支持最大 1M token 上下文[^1] - **历史截断策略**: ```python # 保留最近10轮对话 if len(chat.history) > 20: # 10轮对话=20条消息 chat.history = chat.history[-20:] ``` #### 二、常见问题解决 1. **上下文丢失问题** **症状**:模型忘记之前的对话 **解决方案**: - 检查是否每次调用都传递了完整 `chat.history` - 验证 token 计数是否超限: ```python import tiktoken encoder = tiktoken.encoding_for_model("gpt-4") tokens = encoder.encode(str(chat.history)) print(len(tokens)) # 需小于模型上限 ``` 2. **历史记录污染** **场景**:用户输入包含敏感数据 **清理方法**: ```python def clean_history(history): return [msg for msg in history if not is_sensitive(msg["parts"][0])] ``` 3. **性能优化** - 使用 `stream=True` 流式传输减少延迟 - 对长历史启用摘要功能: ```python summary = model.generate_content("总结对话要点: " + str(history[-5:])) new_history = [{"role": "system", "parts": [summary.text]}] ``` #### 三、最佳实践 1. **混合历史策略** ```mermaid graph LR A[新对话] --> B{历史长度>阈值?} B -->|是| C[摘要前5轮+完整后5轮] B -->|否| D[使用完整历史] ``` 2. **元数据存储** 建议将历史记录与会话元数据(如 session_id)共同存储: ```python # Firebase 存储示例 firestore.collection("chats").document(session_id).set({ "history": chat.history, "last_updated": firestore.SERVER_TIMESTAMP }) ``` > **重要提示**:Gemini 1.5 支持原生文件处理(PDF/Word),可将文档作为历史上下文传入[^1]: > ```python > response = chat.send_message( > "总结此文档", > file=open("report.pdf", "rb") > ) > ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值