Song Jiang's rank list

Song Jiang's rank list

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 512000/512000 K (Java/Others)
Total Submission(s): 14    Accepted Submission(s): 8


Problem Description
《Shui Hu Zhuan》,also 《Water Margin》was written by Shi Nai'an -- an writer of Yuan and Ming dynasty. 《Shui Hu Zhuan》is one of the Four Great Classical Novels of Chinese literature. It tells a story about 108 outlaws. They came from different backgrounds (including scholars, fishermen, imperial drill instructors etc.), and all of them eventually came to occupy Mout Liang(or Liangshan Marsh) and elected Song Jiang as their leader.

In order to encourage his military officers, Song Jiang always made a rank list after every battle. In the rank list, all 108 outlaws were ranked by the number of enemies he/she killed in the battle. The more enemies one killed, one's rank is higher. If two outlaws killed the same number of enemies, the one whose name is smaller in alphabet order had higher rank. Now please help Song Jiang to make the rank list and answer some queries based on the rank list.
 

 

Input
There are no more than 20 test cases.

For each test case:

The first line is an integer N (0<N<200), indicating that there are N outlaws.

Then N lines follow. Each line contains a string S and an integer K(0<K<300), meaning an outlaw's name and the number of enemies he/she had killed. A name consists only letters, and its length is between 1 and 50(inclusive). Every name is unique. 

The next line is an integer M (0<M<200) ,indicating that there are M queries.

Then M queries follow. Each query is a line containing an outlaw's name. 
The input ends with n = 0
 

 

Output
For each test case, print the rank list first. For this part in the output ,each line contains an outlaw's name and the number of enemies he killed. 

Then, for each name in the query of the input, print the outlaw's rank. Each outlaw had a major rank and a minor rank. One's major rank is one plus the number of outlaws who killed more enemies than him/her did.One's minor rank is one plus the number of outlaws who killed the same number of enemies as he/she did but whose name is smaller in alphabet order than his/hers. For each query, if the minor rank is 1, then print the major rank only. Or else Print the major rank, blank , and then the minor rank. It's guaranteed that each query has an answer for it. 
 

 

Sample Input
5 WuSong 12 LuZhishen 12 SongJiang 13 LuJunyi 1 HuaRong 15 5 WuSong LuJunyi LuZhishen HuaRong SongJiang 0
 

 

Sample Output
HuaRong 15 SongJiang 13 LuZhishen 12 WuSong 12 LuJunyi 1 3 2 5 3 1 2

 

 
 
·这题太坑了,,,不知道排序函数为什么错了。
后来改成:

    if( strcmp(x.name1,y.name1) < 0) return 1;

        else return 0;

才过,不知道原因,但以后还是多注意吧。
 
 
AC Code:
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <string.h>
 6 #include <math.h>
 7 #include <queue>
 8 #include <stack>
 9 #include <stdlib.h>
10 #include <map>
11 using namespace std;
12 #define LL long long 
13 #define sf(a) scanf("%d",&(a));
14 
15 
16 #define N 320
17 
18 struct LNode{
19     char name[55];
20     char name1[55];
21     int num;
22 }f[N];
23 
24 int cmd(const struct LNode x,const struct LNode y){
25     if(x.num == y.num)
26         if( strcmp(x.name1,y.name1) < 0) return 1;
27         else return 0;
28     else return x.num > y.num;  //从小到大顺序排列
29 }
30 void print(int n){
31     for(int i=0;i<n;i++){
32         printf("%s %d\n",f[i].name,f[i].num);
33     }
34 }
35 int main()
36 {
37     int n,m;
38     while(scanf("%d",&n)&& n){
39         for(int i=0;i<n;i++){
40             scanf("%s %d",f[i].name,&f[i].num);
41             for(int j=0;j<=strlen(f[i].name);j++)
42                 if(f[i].name[j]>='A' && f[i].name[j]<='Z') f[i].name1[j] = f[i].name[j] + 32;
43                 else f[i].name1[j] = f[i].name[j];
44         }
45         sort(f,f+n,cmd);
46         scanf("%d",&m);
47         print(n);
48         for(int i=0;i<m;i++){
49             char name[55];
50             scanf("%s",name);
51             //for(int i=0;i<strlen(name);i++) if(name[i]>='A' && name[i]<='Z') name[i] = name[i] + 32;
52             for(int j=0;j<n;j++){
53                 if(strcmp(name,f[j].name)==0){
54 
55                     if(j>0 && f[j-1].num==f[j].num){
56                         int t=1;
57                         for(int k=j-1;k>=0;k--){
58                             if(f[k].num == f[j].num) t++;
59                         }
60                         printf("%d %d",j-t+2,t);
61 
62                     }else{
63                         printf("%d",j+1);
64                     }
65                     printf("\n");
66                 }
67             }
68         }
69     }
70     return 0;
71 }

 

将上述代码放入了Recommenders.py文件中,作为一个自定义工具包。将下列代码中调用scipy包中svd的部分。转为使用Recommenders.py工具包中封装的svd方法。给出修改后的完整代码。import pandas as pd import math as mt import numpy as np from sklearn.model_selection import train_test_split from Recommenders import * from scipy.sparse.linalg import svds from scipy.sparse import coo_matrix from scipy.sparse import csc_matrix # Load and preprocess data triplet_dataset_sub_song_merged = triplet_dataset_sub_song_mergedpd # load dataset triplet_dataset_sub_song_merged_sum_df = triplet_dataset_sub_song_merged[[&#39;user&#39;,&#39;listen_count&#39;]].groupby(&#39;user&#39;).sum().reset_index() triplet_dataset_sub_song_merged_sum_df.rename(columns={&#39;listen_count&#39;:&#39;total_listen_count&#39;},inplace=True) triplet_dataset_sub_song_merged = pd.merge(triplet_dataset_sub_song_merged,triplet_dataset_sub_song_merged_sum_df) triplet_dataset_sub_song_merged[&#39;fractional_play_count&#39;] = triplet_dataset_sub_song_merged[&#39;listen_count&#39;]/triplet_dataset_sub_song_merged[&#39;total_listen_count&#39;] # Convert data to sparse matrix format small_set = triplet_dataset_sub_song_merged user_codes = small_set.user.drop_duplicates().reset_index() song_codes = small_set.song.drop_duplicates().reset_index() user_codes.rename(columns={&#39;index&#39;:&#39;user_index&#39;}, inplace=True) song_codes.rename(columns={&#39;index&#39;:&#39;song_index&#39;}, inplace=True) song_codes[&#39;so_index_value&#39;] = list(song_codes.index) user_codes[&#39;us_index_value&#39;] = list(user_codes.index) small_set = pd.merge(small_set,song_codes,how=&#39;left&#39;) small_set = pd.merge(small_set,user_codes,how=&#39;left&#39;) mat_candidate = small_set[[&#39;us_index_value&#39;,&#39;so_index_value&#39;,&#39;fractional_play_count&#39;]] data_array = mat_candidate.fractional_play_count.values row_array = mat_candidate.us_index_value.values col_array = mat_candidate.so_index_value.values data_sparse = coo_matrix((data_array, (row_array, col_array)),dtype=float) # Compute SVD def compute_svd(urm, K): U, s, Vt = svds(urm, K) dim = (len(s), len(s)) S = np.zeros(dim, dtype=np.float32) for i in range(0, len(s)): S[i,i] = mt.sqrt(s[i]) U = csc_matrix(U, dtype=np.float32) S = csc_matrix(S, dtype=np.float32) Vt = csc_matrix(Vt, dtype=np.float32) return U, S, Vt def compute_estimated_matrix(urm, U, S, Vt, uTest, K, test): rightTerm = S*Vt max_recommendation = 10 estimatedRatings = np.zeros(shape=(MAX_UID, MAX_PID), dtype=np.float16) recomendRatings = np.zeros(shape=(MAX_UID,max_recommendation ), dtype=np.float16) for userTest in uTest: prod = U[userTest, :]*rightTerm estimatedRatings[userTest, :] = prod.todense() recomendRatings[userTest, :] = (-estimatedRatings[userTest, :]).argsort()[:max_recommendation] return recomendRatings K=50 # number of factors urm = data_sparse MAX_PID = urm.shape[1] MAX_UID = urm.shape[0] U, S, Vt = compute_svd(urm, K) # Compute recommendations for test users # Compute recommendations for test users uTest = [1,6,7,8,23] uTest_recommended_items = compute_estimated_matrix(urm, U, S, Vt, uTest, K, True) # Output recommended songs in a dataframe recommendations = pd.DataFrame(columns=[&#39;user&#39;,&#39;song&#39;, &#39;score&#39;,&#39;rank&#39;]) for user in uTest: rank = 1 for song_index in uTest_recommended_items[user, 0:10]: song = small_set.loc[small_set[&#39;so_index_value&#39;] == song_index].iloc[0] # Get song details recommendations = recommendations.append({&#39;user&#39;: user, &#39;song&#39;: song[&#39;title&#39;], &#39;score&#39;: song[&#39;fractional_play_count&#39;], &#39;rank&#39;: rank}, ignore_index=True) rank += 1 display(recommendations)
最新发布
06-07
import pandas as pd import math as mt import numpy as np from sklearn.model_selection import train_test_split from Recommenders import SVDRecommender #import the SVDRecommender class from our custom package # Load and preprocess data triplet_dataset_sub_song_merged = triplet_dataset_sub_song_mergedpd # load dataset triplet_dataset_sub_song_merged_sum_df = triplet_dataset_sub_song_merged[[&#39;user&#39;,&#39;listen_count&#39;]].groupby(&#39;user&#39;).sum().reset_index() triplet_dataset_sub_song_merged_sum_df.rename(columns={&#39;listen_count&#39;:&#39;total_listen_count&#39;},inplace=True) triplet_dataset_sub_song_merged = pd.merge(triplet_dataset_sub_song_merged,triplet_dataset_sub_song_merged_sum_df) triplet_dataset_sub_song_merged[&#39;fractional_play_count&#39;] = triplet_dataset_sub_song_merged[&#39;listen_count&#39;]/triplet_dataset_sub_song_merged[&#39;total_listen_count&#39;] # Convert data to sparse matrix format small_set = triplet_dataset_sub_song_merged user_codes = small_set.user.drop_duplicates().reset_index() song_codes = small_set.song.drop_duplicates().reset_index() user_codes.rename(columns={&#39;index&#39;:&#39;user_index&#39;}, inplace=True) song_codes.rename(columns={&#39;index&#39;:&#39;song_index&#39;}, inplace=True) song_codes[&#39;so_index_value&#39;] = list(song_codes.index) user_codes[&#39;us_index_value&#39;] = list(user_codes.index) small_set = pd.merge(small_set,song_codes,how=&#39;left&#39;) small_set = pd.merge(small_set,user_codes,how=&#39;left&#39;) mat_candidate = small_set[[&#39;us_index_value&#39;,&#39;so_index_value&#39;,&#39;fractional_play_count&#39;]] data_array = mat_candidate.fractional_play_count.values row_array = mat_candidate.us_index_value.values col_array = mat_candidate.so_index_value.values data_sparse = coo_matrix((data_array, (row_array, col_array)),dtype=float) # Compute SVD using our custom package K=50 # number of factors urm = data_sparse MAX_PID = urm.shape[1] MAX_UID = urm.shape[0] recommender = SVDRecommender(K) U, S, Vt = recommender.fit(urm) # Compute recommendations for test users uTest = [1,6,7,8,23] uTest_recommended_items = recommender.recommend(uTest, urm, 10) # Output recommended songs in a dataframe recommendations = pd.DataFrame(columns=[&#39;user&#39;,&#39;song&#39;, &#39;score&#39;,&#39;rank&#39;]) for user in uTest: rank = 1 for song_index in uTest_recommended_items[user, 0:10]: song = small_set.loc[small_set[&#39;so_index_value&#39;] == song_index].iloc[0] # Get song details recommendations = recommendations.append({&#39;user&#39;: user, &#39;song&#39;: song[&#39;title&#39;], &#39;score&#39;: song[&#39;fractional_play_count&#39;], &#39;rank&#39;: rank}, ignore_index=True) rank += 1 display(recommendations)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值