解题报告
1.A还是B
题目描述:
https://www.acwing.com/problem/content/3697/
思路:
直接暴力枚举即可。
代码:
#include<iostream>
using namespace std;
const int N = 1e5 + 10;
char str[N];
int n;
int main(){
int cnt = 0;
scanf("%d",&n);
cin >> str;
for(int i = 0 ; i < n ; i ++ )
if(str[i] == 'A') cnt ++ ;
if(cnt < n - cnt) puts("B");
else if(cnt > n - cnt) puts("A");
else puts("T");
return 0;
}
2.扩充序列
题目描述:
https://www.acwing.com/problem/content/3698/
思路:
枚举几次,找一下规律即可得:
数字m的位置在2^(m - 1) + k * (2^m)上。(其中k为整数)
因此,只需要枚举m,找到恰好满足"(k - 2^(m - 1)) % (2^m) == 0"的m然后再输出即可。
注意使用long long。
代码:
#include<iostream>
#include<cmath>
using namespace std;
typedef long long LL;
int n;
LL k;
int main(){
scanf("%d%lld",&n,&k);
if(k % 2 == 1){
printf("1");
return 0;
}
if(k == pow(2,n)){
printf("%d",n + 1);
return 0;
}
for(LL i = 2 ; i <= n ; i ++ ){
LL num1 = pow(2,i);
LL num2 = num1 >> 1;
if(k % num1 % num2 == 0 && k % num1 != 0){
printf("%d",i);
return 0;
}
}
return 0;
}
构造有向无环图:
题目描述:
https://www.acwing.com/problem/content/3699/
思路:
显然,可以用拓扑排序判断能否形成有向无环图。
如果所有已经有向的边可以完成拓扑排序,则可以形成有向无环图,反之则不行。
代码:
#include<iostream>
#include<cstring>
using namespace std;
const int N = 2e5 + 10;
int h[N],ne[N],to[N],idx;
int d[N]; //d数组用于存储每个点的入度
int q[N],S[N]; //q数组用于存储拓扑排序结果,S数组用于存储每个节点在q中的编号
int n,m,T;
struct Edge{
int x,y; //表示x->y的一条边
}edges[N];
void add(int u,int v){
to[idx] = v;
ne[idx] = h[u];
h[u] = idx ++ ;
}
bool toposort(){
int hh = 0,tt = -1;
for(int i = 1 ; i <= n ; i ++ )
if(!d[i])
q[ ++ tt] = i,S[i] = tt;
while(hh <= tt){
int t = q[hh ++ ];
for(int i = h[t] ; i != -1 ; i = ne[i]){
int j = to[i];
if( -- d[j] == 0){
q[ ++ tt] = j;
S[j] = tt;
}
}
}
return tt == n - 1;
}
void solve(){
scanf("%d%d",&n,&m);
idx = 0;
memset(h,-1,(n + 1) * 4);
memset(d,0,(n + 1) * 4);
for(int i = 0 ; i < m ;i ++ ){
int t,x,y;
scanf("%d%d%d",&t,&x,&y);
if(t){
add(x,y);
d[y] ++ ;
}
edges[i] = {x,y};
}
if(!toposort())
printf("NO\n");
else{
printf("YES\n");
for(int i = 0 ; i < m ;i ++ ){
auto &t = edges[i];
if(S[t.x] < S[t.y]) printf("%d %d\n",t.x,t.y);
else printf("%d %d\n",t.y,t.x);
}
}
}
int main(){
scanf("%d",&T);
while(T -- ) solve();
return 0;
}