題目鏈接
A Required Remainder
這個題用循環做超時好多次,最後發現用不到循環……
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
int t;
cin >> t;
ll x,n,k,y;
while(t--)
{
bool flag = 0;
cin >> x >> y >> n;
int tt = n%x;
if(tt>=y)
{
cout << n-tt+y <<endl;
}else{
cout << n-tt-x+y <<endl;
}
}
return 0;
}
B Multiply by 2, divide by 6
因爲對數的操作只能×2或者÷6,所以只需要分析能否被3整除即可,後續再進行判斷即可。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
int t;
cin >> t;
ll x,n,k,y;
while(t--)
{
ll ans = 0;
cin >> n;
if(n==1)
cout << 0 <<endl;
else if(n%3!=0)
cout << -1 <<endl;
else{
while(n%6==0)
{
ans++;
n/=6;
}
while(n%3==0)
{
ans += 2;
n/=3;
}
if(n==1)
cout << ans <<endl;
else
cout << -1 <<endl;
}
}
return 0;
}
C Move Brackets
括號匹配問題,用stack做的
#include<bits/stdc++.h>
#include<stack>
using namespace std;
#define ll long long
int main()
{
int t;
cin >> t;
int n;
string s;
while(t--)
{
stack<int>st;
cin >> n >> s;
int ans=0;
for(int i=0;i<n;i++)
{
if(s[i]=='(')
st.push(1);
else{
if(st.empty())
ans++;
else
st.pop();
}
}
cout << ans <<endl;
}
return 0;
}
D Zero Remainder Array
這個題就是查找、記錄重複的問題。
首先記錄數組中每個元素的操作數k−%k,若有重複,則找重複次數最多的那個操作數,操作的次數即[ (次數 - 1) × k + 該操作數 ].
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=2e5+10;
ll a[maxn],k,b[maxn],num[maxn],top;
int main()
{
ll t,n;
cin>>t;
while(t--)
{
top=0;
cin>>n>>k;
int flag=1;
for(int i=1;i<=n;i++)
{
cin >> a[i];
a[i]%=k;
if(a[i]) flag=0;
a[i] = k-a[i];
}
if(flag)
{
cout<<0<<endl;
continue;
}
sort(a+1,a+1+n);
ll last=a[1],temp=1,maxx=0;
for(int i=2;i<=n;i++)
{
if(a[i]==k) break;
if(a[i]==last) temp++;
else
{
maxx=max(maxx,temp);
b[++top]=last,num[top]=temp;
last=a[i],temp=1;
}
}
b[++top]=last,num[top]=temp;
maxx=max(maxx,temp);
ll ans=0;
for(int i=1;i<=top;i++)
if(num[i]==maxx)
ans=max(ans,(maxx-1)*k+b[i]);
cout<<ans+1<<endl;
}
}