当前位置 博文首页 > LJ的博客:石器时代 —— Leetcode刷题日记 (三 面试题相关)
随机刷题
且矿石数量相差不超过1个
条件!#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <limits.h> // INT_MIN
using namespace std;
#define MAX_NUM 101
int solution(int n, int weight[]) {
int sum = 0, h_sum, h_n = (n + 1) / 2;
for (int i = 0; i < n; i++) sum += weight[i];
h_sum = sum / 2;
vector<vector<int>> dp(h_sum + 1, vector<int>(h_n + 1, INT_MIN));
for (int i = 0; i <= h_sum; i++) dp[i][0] = 0;
for (int i = 0; i < n; i++) {
auto tmp = dp; // 避免覆盖!
for (int j = weight[i]; j <= h_sum; j++) {
for (int k = 1; k <= h_n; k++)
tmp[j][k] = max(tmp[j][k], dp[j-weight[i]][k-1]+weight[i]);
}
dp = tmp;
}
if (n % 2) return sum - 2 * max(dp[h_sum][h_n], dp[h_sum][h_n-1]);
else return sum - 2 * dp[h_sum][h_n];
}
int main()
{
string str("");
getline(cin, str);
int a[MAX_NUM];
int i = 0;
char *p;
int count = 0;
const char* strs = str.c_str();
p = strtok((char *)strs, " ");
while(p) {
a[i] = atoi(p);
count++;
p = strtok(NULL, " ");
i++;
if(i >= MAX_NUM)
break;
}
int result = solution(count, a);
cout << result << endl;
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
typedef struct _node
{
int num;
struct _node * next;
}node;
void solution(int N, int M)
{
if (N < 1 || M < 1) return;
vector<int> rows(N, 0);
for (int i = 0; i < N; i++) rows[i] = i + 1;
int pos = 0;
while (rows.size() > 0) {
pos += M - 1;
pos %= rows.size();
cout << rows[pos] << " ";
rows.erase(rows.begin() + pos);
}
cout << endl;
}
int main()
{
int N;
int M;
string str("");
getline(cin, str);
char *p;
const char* strs = str.c_str();
p = strtok((char *)strs, " ");
N = atoi(p);
p = strtok(NULL, " ");
M = atoi(p);
solution(N, M);
return 0;
}
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int solution(int a[], int N)
{
int pre = 0, cur = 0;
int steps = 0;
for (int i = 0; i < N - 1; i++) {
cur = max(cur, i+a[i]);
if (pre == i) {
pre = cur;
steps++;
if (cur >= N - 1)
break;
}
}
return pre >= N - 1 ? steps : -1;
}
int main()
{
string str("");
getline(cin, str);
int a[2000];
int i = 0;
char *p;
int count = 0;
const char* strs = str.c_str();
p = strtok((char *)strs, " ");
while(p)
{
a[i] = atoi(p);
count++;
p = strtok(NULL, " ");
i++;
if(i >= 2000)
break;
}
int num = solution(a, count);
cout << num << endl;
return 0;
}
//write code here
vector<vector<vector<int>>> dp(countOfApp + 1,vector<vector<int