杭电OJ(HDU)-ACMSteps-Chapter Three-《FatMouse' Trade》《今年暑假不AC》《排名》《开门人和关门人》

本文深入探讨了编程领域的核心概念和技术,包括数据结构、算法、软件开发工具、测试方法等,旨在帮助程序员提升技能,从基础到进阶。涵盖前端开发、后端开发、移动开发、游戏开发等多个技术方向,提供了实用的编程技巧和实践经验。


http://acm.hdu.edu.cn/game/entry/problem/list.php?chapterid=1§ionid=3

1.3.1 FatMouse' Trade
#include <algorithm>
/*
题意:价值/代价的比值来排序,买比值大的。
Sample Input
5 3 
7 2
4 3
5 2
20 3 25 18 24 15 15 10 -1 -1
 
Sample Output
13.333 31.500
*/
#include<stdio.h>
#include<stdlib.h>

const int MAXN = 1010;
struct node
{
    double j,f;
    double r;
}a[MAXN];
int cmp(const void *a,const void *b)
{
    struct node *c=(node *)a;
    struct node *d=(node *)b;
    if(c->r > d->r) return -1;
    else return 1;
}    
int main()
{
    int N;
    double M;
    double ans;
    while(scanf("%lf%d",&M,&N))
    {
        if(M==-1&&N==-1) break;
        for(int i=0;i<N;i++)
        {
           scanf("%lf%lf",&a[i].j,&a[i].f);
           a[i].r=(double)a[i].j/a[i].f;
        }    
        qsort(a,N,sizeof(a[0]),cmp);
        ans=0;
        for(int i=0;i<N;i++)
        {
            if(M>=a[i].f)
            {
                ans+=a[i].j;
                M-=a[i].f;
            }    
            else 
            {
                ans+=(a[i].j/a[i].f)*M;
                break;
            }    
        }   
        printf("%.3lf\n",ans); 
    }    
    return 0;
}    

1.3.2	今年暑假不AC
*
Sample Input
12
1 3
3 4
0 7
3 8
15 19
15 20
10 15
8 18
6 12
5 10
4 14
2 9
0
 
Sample Output
5
*/
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
struct ti  
{  
    int s, e;  
};  
  
int compare(const void *a, const void *b);  
  
int main()  
{  
    int i, n, k;  
    struct ti tis[101], temp[101];  
  
    while(scanf("%d", &n) != EOF)  
    {  
        if(n == 0)  
            break;  
  
        for(i = 0; i < n; i ++)  
        {  
            scanf("%d %d", &tis[i].s, &tis[i].e);  
        }  
  
        qsort(tis, n, sizeof(tis[0]), compare);  
  
        k = 0;  
        temp[k] = tis[0];  
  
        for(i = 1; i < n; i ++)  
        {  
            if(tis[i].s >= temp[k].e)  
                temp[++ k] = tis[i];  
        }  
        printf("%d\n", k + 1);  
    }  
    return 0;  
}  
  
int compare(const void *a, const void *b)  
{  
    const struct ti *p = (ti*)a;  
    const struct ti *q = (ti*)b;  
  
    return p->e - q->e;  
}  

1.3.3	排名

#include <string>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define N 1000
int que[10];
struct node
{
	char name[20];
	int num;
	int score;
}stu[N];

bool cmp(const node& a, const node& b)
{
	if (a.score == b.score)
	{
		return strcmp(a.name, b.name) < 0 ? 1:0;
	}
	else
	{
		return a.score > b.score;
	}
}

/* 联系字典序:第1行给出考生人数N ( 0 < N < 1000 )、考题数M ( 0 < M < = 10 )、分数线(正整数)G;
第2行排序给出第1题至第M题的正整数分值;
以下N行,每行给出一名考生准考证号(长度不超过20的字符串)、该生解决的题目总数m、以及这m道题的题号 
4 5 25
10 10 12 13 15
CS004 3 5 1 3
CS003 5 2 4 1 3 5
CS002 2 1 2
CS001 3 2 3 5
*/
int main()
{
	int student, question, judge, x, count;
	while(scanf("%d", &student),student)
	{
		count = 0;
		for (int i = 1; i <= student;++i)
		{
			stu[i].score = 0;
			stu[i].num = 0;
		}
		scanf("%d%d",&question, &judge);
		for (int i = 1;i <= question;++i)
		{
			scanf("%d",&que[i]);
		}
		for (int i = 1;i <= student;++i)
		{
			scanf("%s%d",&stu[i].name,&stu[i].num);
			while(stu[i].num--)
			{
				scanf("%d",&x);
				stu[i].score += que[x];
			}
			if (stu[i].score >= judge)
				count ++;
		}
		sort(stu+1,stu+1+student,cmp);
		printf("%d\n",count);
		for (int i = 1;i <= student;++i)
		{
			if (stu[i].score >= judge)
				printf("%s %d\n",stu[i].name, stu[i].score);
			else
				break;
		}
	}
	return 0;
}

1.3.4 开门人和关门人
#include "stdafx.h"

#include <iostream>  
#include <string>  
using namespace std ;  
  
  
struct node  
{  
    string name, timee;  
}maxt, mint;//记录最大和最小的结构体  
  
int main()  
{  
    int t, n;  
    string s,mis, mas;  
    cin>>t;  
  
  
    while (t--)  
    {  
        cin>>n;  
        n--;  
        cin>>s>>mint.timee>>maxt.timee;  
        mint.name = maxt.name = s;  
  
        while (n--)  
        {  
            cin>>s>>mis>>mas;  
            if (mis < mint.timee)  
            {  
                mint.name = s;  
                mint.timee = mis;  
            }  
            if (mas > maxt.timee)  
            {  
                maxt.name = s;  
                maxt.timee = mas;  
            }  
        }  
  
        cout<<mint.name<<" "<<maxt.name<<endl;  
    }  
  
    return 0;  
}






### Viterbi Algorithm Explanation The **Viterbi algorithm** is a dynamic programming technique used primarily for finding the most likely sequence of hidden states—called the *Viterbi path*—in models such as Hidden Markov Models (HMMs). It operates based on two key probabilities: 1. The **transition probability**, which defines the likelihood of moving from one state to another. 2. The **emission probability**, which represents the likelihood of observing a particular symbol given a specific state. Mathematically, the goal is to maximize the joint probability \( P(L|O) \), where \( L \) denotes the label sequence and \( O \) represents the observation sequence. This can be expressed using Bayes' theorem: \[ P(L|O) = \frac{P(O|L)P(L)}{P(O)} \] Here, \( P(O|L) \) refers to the emission probability, while \( P(L) \) corresponds to the transition probability between labels[^4]. To compute this efficiently, the Viterbi algorithm employs recursion over time steps, maintaining both the maximum probability at each step and the corresponding optimal predecessor state. Below is an outline of its core components: #### Key Components - At any point in time \( t \), let \( v_t(j) \) denote the highest probability along a single path ending with state \( j \). - Let \( p_t(j) \) store the index of the previous state leading optimally to state \( j \). These values are updated iteratively according to the following equations: \[ v_{t}(j)=\max _{1 \leq i \leq N}\left[v_{t-1}(i)a(i,j)\right]b(j,o_{t}) \] Where: - \( a(i,j) \): Transition probability from state \( i \) to state \( j \), - \( b(j,o_t) \): Emission probability of emitting observation \( o_t \) when in state \( j \)[^4]. Once all sequences have been processed through the final stage, traceback begins starting from the terminal node having maximal value among possible end-states until reaching initial conditions. ### Python Implementation Example Below demonstrates a basic implementation utilizing numpy arrays for clarity purposes only; actual applications may require optimizations depending upon use cases. ```python import numpy as np def viterbi(obs_seq, trans_prob, emit_prob, init_prob): T = len(obs_seq) num_states = len(trans_prob) # Initialize matrices prob_matrix = np.zeros((T, num_states)) prev_state = np.zeros((T, num_states)) # Initialization Step for s in range(num_states): prob_matrix[0][s] = init_prob[s] * emit_prob[s][obs_seq[0]] # Recursion Steps for t in range(1, T): for s in range(num_states): max_val = -np.inf best_prev = None for sprev in range(num_states): val = prob_matrix[t-1][sprev]*trans_prob[sprev][s] if val > max_val: max_val = val best_prev = sprev prob_matrix[t][s] = max_val * emit_prob[s][obs_seq[t]] prev_state[t][s] = best_prev # Termination & Traceback last_best = np.argmax(prob_matrix[-1]) seq = [last_best] for t in reversed(range(T-1)): last_best = int(prev_state[t+1][last_best]) seq.append(last_best) return list(reversed(seq)), prob_matrix[-1][seq[-1]] # Sample Data Setup states = ('Rainy', 'Sunny') observations = ['walk', 'shop', 'clean'] start_probability = {'Rainy': 0.6, 'Sunny': 0.4} transition_probability = { 'Rainy' : {'Rainy': 0.7, 'Sunny': 0.3}, 'Sunny' : {'Rainy': 0.4, 'Sunny': 0.6}, } emission_probability = { 'Rainy' : {'walk': 0.1, 'shop': 0.4, 'clean': 0.5}, 'Sunny' : {'walk': 0.6, 'shop': 0.3, 'clean': 0.1}, } observation_map = {act:i for i, act in enumerate(observations)} init_p = np.array([start_probability[state] for state in states]) trn_p = np.array([[transition_probability[a][b] for b in states] for a in states]) emit_p = np.array([[emission_probability[a][b] for b in observations] for a in states]) sequence_indices = [observation_map[o] for o in ["walk", "shop"]] result_sequence, result_prob = viterbi(sequence_indices, trn_p, emit_p, init_p) print("Most probable sequence:", [states[i] for i in result_sequence], "\nProbability:", result_prob) ``` This script initializes parameters representing weather transitions alongside activities performed under certain circumstances before executing `viterbi` function call providing results accordingly.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小雄哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值