hnucm_oj 算法分析与设计 练习13
问题 A: 迷路的牛牛
题目描述
牛牛去犇犇老师家补课,出门的时候面向北方,但是现在他迷路了。虽然他手里有一张地图,但是他需要知道自己面向哪个方向,请你帮帮他。
输入
每个输入包含一个测试用例。
每个测试用例的第一行包含一个正整数,表示转方向的次数N(N<=1000)。
接下来的一行包含一个长度为N的字符串,由L和R组成,L表示向左转,R表示向右转。
输出
输出牛牛最后面向的方向,N表示北,S表示南,E表示东,W表示西。
样例输入
3
LRR
样例输出
E
代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int n = sc.nextInt();
sc.nextLine();
String a = sc.nextLine();
char[] b = a.toCharArray();
int L=0,R=0,c=0;
for(int i=0;i<n;i++) {
if(b[i]=='R') {
R++;
}
else {
L++;
}
}
if(R>L) {
c=(R-L)%4;
if(c==0) {
System.out.println("N");
}
else if(c==1) {
System.out.println("E");
}
else if(c==2) {
System.out.println("S");
}
else if(c==3) {
System.out.println("W");
}
}
else {
c=(L-R)%4;
if(c==0) {
System.out.println("N");
}
else if(c==1) {
System.out.println("W");
}
else if(c==2) {
System.out.println("S");
}
else if(c==3) {
System.out.println("E");
}
}
}
}
}
问题 B: 工作单位
题目描述
在某个城市中住着n个人,现在给定关于这n个人的m条信息(即某2个人认识)。
假设所有认识的人一定属于同一个单位,请计算该城市有多少个单位?
输入
第1行的第1个值表示总人数n,第2个值表示总信息数m;第2行开始为具体的认识关系信息
输出
单位的个数
样例输入
10 4
2 3
4 5
4 8
5 8
样例输出
7
代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
int n = sc.nextInt();
int m = sc.nextInt();
int[] a = new int[n+1];
int count=1;
for(int i=0;i<m;i++) {
int j = sc.nextInt();
int k = sc.nextInt();
if(a[j]==0&&a[k]==0) {
a[j]=count;
a[k]=count;
count++;
}
else if(a[j]!=0&&a[k]==0) {
a[k]=a[j];
}
else if(a[k]!=0&&a[j]==0) {
a[j]=a[k];