C.Rational Resistance
題意:給出一個分數,分子爲a,分母爲b,求組成該電阻的最小個數。電阻有串聯並聯兩種方式,初始電阻均爲1.
思路:因爲串聯越多,電阻增大;並聯越多,電阻減小。
// [a/b]表示int(a/b),a/b表示爲分數b分之a;
例如a=21,b=8;那麼其一定是由[21/8]個電阻再加上21/8-2=5/8,即使8/5的倒數,那麼8/5又是由[8/5]加上3/5。
同理5/3=[5/3]+2/3;3/2=[3/2]+1/2;2/1=2;
所以21/8=[21/8]+[8/5]+[5/3]+[3/2]+[2/1]=2+1+1+1+2=7;
注意數據的範圍。
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long ll;
int main()
{
ll a,b,ans;
ans=0;
cin>>a>>b;
if(a<b)swap(a,b);
while(a&&b)
{
if(a<b)swap(a,b);
ans+=a/b;
a-=a/b*b;
}
cout<<ans<<endl;
}
D.Alternating Current
題意:兩根“+”,“-”的電線,給你一個只含有“+”“-”的字符串,“+”表示+的電線壓在-的上面,反之。
問給出的電線交叉方式能否互不纏繞,能輸出Yes,不能輸出No。
思路:兩個相鄰且相同的字符可以把兩根線分開。例如-++-,不斷的理清相鄰且相同的字符,-++- -> --。所以可以利用棧先進後出的特點,遍歷字符串,與棧頭不同則加入棧,反之則pop。
#include<bits/stdc++.h>
using namespace std;
char str[100005];
int main(){
while(~scanf("%s",str)){
stack<char>q;
int n=strlen(str);
for(int i=0;i<n;i++){
if(q.empty()||str[i]!=q.top())q.push(str[i]);
else{
q.pop();
}
}
if(q.empty())printf("Yes\n");
else printf("No\n");
}
}