Characters with Hash

Mur loves hash algorithm, and he sometimes encrypt another one's name, and call him with that encrypted value. For instance, he calls Kimura KMR, and calls Suzuki YJSNPI. One day he read a book about SHA-256256 , which can transit a string into just 256256 bits. Mur thought that is really cool, and he came up with a new algorithm to do the similar work. The algorithm works this way: first we choose a single letter L as the seed, and for the input(you can regard the input as a string ss, s[i]s[i] represents the iith character in the string) we calculates the value(|(int) L - s[i]|∣(int)L−s[i]∣), and write down the number(keeping leading zero. The length of each answer equals to 2because the string only contains letters and numbers). Numbers writes from left to right, finally transfer all digits into a single integer(without leading zero(ss)). For instance, if we choose 'z' as the seed, the string "oMl" becomes "11 45 14".

It's easy to find out that the algorithm cannot transfer any input string into the same length. Though in despair, Mur still wants to know the length of the answer the algorithm produces. Due to the silliness of Mur, he can even not figure out this, so you are assigned with the work to calculate the answer.

Input

First line a integer TT , the number of test cases (T \le 10)(T≤10).

For each test case:

First line contains a integer NN and a character zz, (N \le 1000000)(N≤1000000).

Second line contains a string with length NN . Problem makes sure that all characters referred in the problem are only letters.

Output

A single number which gives the answer.

样例输入复制

2
3 z
oMl
6 Y
YJSNPI

样例输出复制

6
10

题目来源

ACM-ICPC 2018 徐州赛区网络预赛

 

这道题如果英语水平不太好的话可能就不能完全理解题意(我就是),尤其是一会保留前导零,一会不保留前导零,我当时就被它给弄晕啦,后来问了大神才明白了题意,他的意思就是对字符串中的每个字符从前往后按题中的公式运算,他说保留前导零,并且公式结果长度为2,这样的货就是说如果计算结果为1的话那么应该写成01,最后再将所有的结果合并起来,而合并起来的这个结果是不保留前导零的,比如三个结果分别是00 10 12 那么合并后的结果是1012为4为;

 

#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<stdio.h>
using namespace std;
struct Store {//a,b代表每一个结果的两位数是不是为零,false为零,true不为零
	bool a=false;
	bool b=false;
}store[10000001];
int main()
{
	
	//freopen("own.txt", "r", stdin);
	int t;
	cin >> t;
	while (t--) {
		int n;
		char z;
		bool flag =false;
		cin >> n >> z;
		string str;
		cin >> str;
		for (int i = 0; i < n; i++) {
			int x = abs((int)z - str[i]);
			if (x >= 10) {//如果运算的结果为两位数,那么肯定是ab都为true
				store[i].a = true;
				store[i].b = true;
			}
			else if (x > 0 && x <= 9) {//如果是一位数,那么就是a假b真
				store[i].a = false;
				store[i].b = true;
			}
			else if (x == 0) {//等于零就都是假
				store[i].a = false;
				store[i].b = false;
			}
	}
		int ans = 0;
		for (int i = 0; i < n; i++) {
			if (flag) {//flag用来辅助判断有没有前导零,如果没有的话,以后的数就可以放心的加2啦
				ans += 2;
			}
			else {
				if (store[i].a == true) {//下边两个if语句是从最后合并的结果中找到第一个不是false的地方并计数
					ans++;
					flag = true;
				}
			if (store[i].b == true) {
				ans++;
				flag = true;
			}
			}

		}
		if (ans == 0)
			cout << 1 << endl;
		else
		cout << ans << endl;
	}
	
	return 0;
}

 

import asyncio from datetime import timedelta import httpx import json import os import torch import uvicorn from fastapi import Depends, FastAPI, Request, Response from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from jinja2 import Environment, FileSystemLoader from dotenv import load_dotenv from pathlib import Path from transformers import AutoModelForCausalLM, AutoTokenizer from jwt_handler import ( get_current_user_id, verify_password, get_password_hash, create_access_token ) import database BASE_DIR = Path(__file__).resolve().parent.parent # 项目根目录 FRONTEND_DIR = BASE_DIR / "frontend" app = FastAPI() load_dotenv(dotenv_path=BASE_DIR / "backend" / ".env") # 挂载静态资源 app.mount("/static", StaticFiles(directory=str(FRONTEND_DIR)), name="static") templates = Jinja2Templates(directory=str(FRONTEND_DIR)) template_env = Environment(loader=FileSystemLoader(str(FRONTEND_DIR))) model, tokenizer = None, None def load_model(): model_name = str(BASE_DIR / "model/deepseek-coder-1.3b-instruct") print("Loading tokenizer...") tok = AutoTokenizer.from_pretrained(model_name) print("Loading model...") m = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, device_map="auto", low_cpu_mem_usage=True ).eval() return m, tok async def start_load(): global model, tokenizer loop = asyncio.get_event_loop() model, tokenizer = await loop.run_in_executor(None, load_model) print("✅ Model loaded during startup!") @app.get("/", response_class=HTMLResponse) async def home(): template = template_env.get_template("home.html") content = template.render() return HTMLResponse(content=content) @app.get("/login", response_class=HTMLResponse) async def login_page(): template = template_env.get_template("login.html") content = template.render() return HTMLResponse(content=content) @app.post("/login") async def login(request: Request): data = await request.json() account = data.get("account") password = data.get("password") hash_password = get_password_hash(password) if not account or not password: return JSONResponse( {"success": False, "message": "请输入用户名和密码"}, status_code=400 ) # 从数据库查找用户 result = database.check_users(account,hash_password) user_id, hashed_password_from_db = result # 核对密码 if not verify_password(password, hashed_password_from_db): return JSONResponse( {"success": False, "message": "用户名或密码错误"}, status_code=401 ) # 创建 JWT Token access_token_expires = timedelta(minutes=int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", 30))) access_token = create_access_token( data={"sub": str(user_id)}, # subject 是用户 ID expires_delta=access_token_expires ) # ✅ 正确方式:创建响应对象并设置 HttpOnly Cookie response = JSONResponse({ "success": True, "account": account }) response.set_cookie( key="access_token", value=access_token, httponly=True, secure=False, # 开发环境设为 False,生产改为 True (HTTPS) samesite="lax", max_age=access_token_expires.total_seconds() # 自动同步过期时间 ) return response @app.get("/user2", response_class=HTMLResponse) async def chat_page(request: Request, current_user_id: str = Depends(get_current_user_id)): print(current_user_id) if not current_user_id: return RedirectResponse(url="/login") template = template_env.get_template("myapp.html") characters = database.get_all_characters() characters_json = json.dumps([ {"id": c["id"], "name": c["name"], "trait": c["trait"]} for c in characters ], ensure_ascii=False) content = template.render(characters=characters, characters_json=characters_json) print(1) return HTMLResponse(content=content) @app.post("/user2/chat") async def dashscope_chat( request: Request, current_user_id: str = Depends(get_current_user_id) ): if not current_user_id: return JSONResponse({"error": "未授权访问"}, status_code=401) data = await request.json() character_id = data.get("character_id") user_message = data.get("message") if not character_id or not user_message: return JSONResponse({"error": "缺少必要参数"}, status_code=400) # 查询角色信息 character = database.get_character_by_id(character_id) if not character: return JSONResponse({"error": "角色不存在"}, status_code=404) system_prompt = f""" 你正在扮演 {character['name']}。 人物设定:{character['trait']} 请始终以这个角色的身份、语气和思维方式回答问题。 不要暴露你是 AI 的事实。 """.strip() try: API_KEY = os.getenv("DASHSCOPE_API_KEY") if not API_KEY: return JSONResponse({"error": "API密钥未配置"}, status_code=500) headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json", "Accept": "application/json" } payload = { "model": "qwen-plus", "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_message} ], "temperature": 0.85, "top_p": 0.95, "max_tokens": 512, "stream": False } async with httpx.AsyncClient(timeout=30.0) as client: resp = await client.post( "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions", json=payload, headers=headers ) if resp.status_code != 200: error_detail = resp.text return JSONResponse( {"error": f"远程API错误 [{resp.status_code}]", "detail": error_detail}, status_code=resp.status_code ) result = resp.json() reply = result["choices"][0]["message"]["content"].strip() # 保存对话记录 database.save_conversation(int(current_user_id), character_id, user_message, reply) return JSONResponse({"reply": reply}) except Exception as e: import traceback error_msg = traceback.format_exc() return JSONResponse( {"error": f"请求失败: {str(e)}", "detail": error_msg}, status_code=500 ) if __name__ == "__main__": uvicorn.run("myapp:app", host="127.0.0.1", port=8000, reload=True) 帮我添加调试功能,方便我跟踪访问用户
09-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值