The first link: take coins
The first question is basically a free gift, as long as the parity is judged.
class Solution {
public:
int minCount(vector<int>& coins) {
int ans=0;
for(int i=0;i<coins.size();i++)
{
if(coins[i]%2==0)
{
ans+=coins[i]/2;
}
else
{
ans+=coins[i]/2;
ans++;
}
}
return ans;
}
};
The second question link: transfer information
The second question I thought was to use the adjacency matrix to do it, but it can still be passed. The difficulty is mainly the power operation of the matrix. It should be optimized here, but direct submission can still double 100%.
class Solution {
public:
vector<vector<int>> Mult(vector<vector<int>> a,vector<vector<int>> b) {
int n = a.size(), m = a[0].size(), p = b[0].size();
vector<vector<int> > result(n,vector<int>(n,0));
for(int i=0; i<n; i++) {
for(int j=0; j<p; j++) {
for(int k=0; k<m; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
return result;
}
int numWays(int n, vector<vector<int>>& relation, int k) {
vector<vector<int>>g(n,vector<int>(n,0)),ans;
for(int i=0;i<relation.size();i++)
{
g[relation[i][0]][relation[i][1]]++;
}
ans=g;
for(int i=1;i<k;i++)
{
ans=Mult(ans,g);
}
return ans[0][n-1];
}
};
The third question link: plot trigger time
At that time, I didn’t think of using a two-division method to do this question. It was really careless. After writing the violent simulation, I found that it would time out, so I got stuck:
first post a code written at the time that would time out :
class Solution {
public:
vector<int> getTriggerTime(vector<vector<int>>& increase, vector<vector<int>>& requirements) {
int C=0,R=0,H=0;
vector<int> ans(requirements.size(),-1);
int vis[100000]={
0};
int head=0,temp=1000000;
for(int i=0;i<increase.size();i++)
{
C+=increase[i][0];
R+=increase[i][1];
H+=increase[i][2];
for(int j=head;j<requirements.size();j++)
{
if(C>=requirements[j][0]&&R>=requirements[j][1]&&H>=requirements[j][2]&&!vis[j])
{
if(!i&&!j)
{
vis[j]=-2;
continue;
}
vis[j]=i+1;
}
temp=min(temp,j);
}
head=temp;
}
for(int i=0;i<requirements.size();i++)
{
if(vis[i]==-2)
{
ans[i]=0;
continue;
}
if(vis[i])
{
ans[i]=vis[i];
}
}
return ans;
}
};
The correct code is:
class Solution {
public:
vector<int> getTriggerTime(vector<vector<int>>& increase, vector<vector<int>>& requirements) {
vector<vector<int>> s(increase.size()+1,vector<int>(3,0));
for(int i=0;i<increase.size();i++){
for(int j=0;j<3;j++){
s[i+1][j] = s[i][j] + increase[i][j];
}
}
vector<int> ans;
for(auto v:requirements){
int l=0, r = increase.size();
while(l<r){
int m = (l+r)/2;
if(s[m][0]>=v[0]&&s[m][1]>=v[1]&&s[m][2]>=v[2])
r = m;
else
l = m+1;
}
if(s[l][0]>=v[0]&&s[l][1]>=v[1]&&s[l][2]>=v[2])
ans.push_back(l);
else
ans.push_back(-1);
}
return ans;
}
};